コード例 #1
0
ファイル: Training.py プロジェクト: betaros/traffic_sign
 def __init__(self):
     """
     Initialising
     """
     self.misc = Misc()
     self.training_path = os.path.join(self.misc.project_root, "dataset",
                                       "GTSRB", "Final_Training", "Images")
     self.test_path = os.path.join(self.misc.project_root, "dataset",
                                   "GTSRB", "Final_Test", "Images")
コード例 #2
0
 def get_tile(self):
     temp = []
     for i in self.results:
         temp.append(
             Misc.TPoint(
                 round(Misc.get_base_x() +
                       Ref.get_int(i, Hook.Actor_WorldX) / 128),
                 round(Misc.get_base_y() +
                       Ref.get_int(i, Hook.Actor_WorldY) / 128)))
     return temp
コード例 #3
0
ファイル: Uimethod.py プロジェクト: xcma/selenium
 def Falsecreenshot(self, casename):
     """截图放到相应路径中"""
     if operation in ["chrome", "firfox", "ie"]:
         cname = casename + datetime.datetime.now().strftime("%Y%m%d.%H%M%S.%f")[:-3]
         # 截图创建路径
         FalseScreenshotPath = Misc.ABSpath() + readConfig(Config_path)["path"]["FalseScreenshot"]
         log.debug(u"读取截图路径:" + str(FalseScreenshotPath))
         Misc.mkdir(path=Misc.ABSpath() + "/Output/Screenshot", name="Fail")
         self.driver.get_screenshot_as_file(FalseScreenshotPath + "%s.png" % cname)
         log.debug(u"False截图成功")
     else:
         log.warning("未执行截图")
コード例 #4
0
ファイル: UiMethods.py プロジェクト: xcma/selenium
 def Falsecreenshot(cls, casename):
     """截图放到相应路径中"""
     if operation in ['chrome', 'firfox', 'ie']:
         cname = casename + datetime.datetime.now().strftime("%Y%m%d.%H%M%S.%f")[:-3]
         # 截图创建路径
         FalseScreenshotPath = Misc.ABSpath()+readConfig(Config_path)['path']['FalseScreenshot']
         log.debug(u'读取截图路径:' + str(FalseScreenshotPath))
         Misc.mkdir(path=Misc.ABSpath()+"/Output/Screenshot", name='Fail')
         cls.driver.get_screenshot_as_file(FalseScreenshotPath+"%s.png" % cname)
         log.debug(u'False截图成功')
     else:
         log.warning('未执行截图')
コード例 #5
0
ファイル: Training.py プロジェクト: betaros/traffic_sign
    def load_images(self, training):
        """
        Load images from datasets
        :param training:
        :return:
        """
        if training:
            self.misc.logger.debug("Training set")
            image_list = self.load_training_image_properties()
        else:
            self.misc.logger.debug("Test set")
            image_list = self.load_training_image_properties()

        for element in image_list:
            self.misc.logger.debug("Class id: %i", element["ClassId"][0])
            for index, row in element.iterrows():
                img_path = os.path.join(self.training_path,
                                        Misc().fill_number(row['ClassId'], 5),
                                        row['Filename'])
                # if index == 0:
                # self.show(img_path, row['Roi.X1'], row['Roi.Y1'], row['Roi.X2'], row['Roi.Y2'])
                self.misc.logger.debug(
                    str(row['ClassId']) + " " + row['Filename'] + " " +
                    str(row['Height']) + " " + str(row['Width']) + " " +
                    str(row['Roi.X1']) + " " + str(row['Roi.Y1']) + " " +
                    str(row['Roi.X2']) + " " + str(row['Roi.Y2']))
        return None
コード例 #6
0
ファイル: Chart.py プロジェクト: xcma/selenium
 def chartStyle(cls):
     all_res_time_dict, all_uptm_dict = Chart.getResTimelList()
     for if_name, res_time_list in all_res_time_dict.items():
         chart = pygal.Line()
         for if_name_1, uptm in all_uptm_dict.items():
             if if_name == if_name_1:
                 uptm_new = []
                 for i in uptm:
                     ti = i.strftime('%H:%M:%S')
                     uptm_new.append(ti)
                 chart.x_labels = uptm_new
         chart.add(if_name, res_time_list)
         # 控制y轴高度
         chart.range = [50, 450]
         Misc.save_as_file(chart.render(), 'chart_'+if_name+'.html', 'w', 'chart')
         chart.teardown()
コード例 #7
0
ファイル: Chart.py プロジェクト: xcma/selenium
    def getResTimelList(cls):
        """
        查询响应时间列表
        :return:[]
        """
        all_res_time = {}
        all_uptm = {}
        path = Misc.ABSpath() + "/Src/Conf/Config.yml"
        all_type = readConfig(path)['Api_all_type']
        for key, type in all_type.items():
            data = Chart.getData(type)
            if data:
                if_name_one = Misc.read_from_file('if_name_one_list')[0]
                # 根据if_name取出对应的res_time_list和uptm_list
                for name in if_name_one:
                    if_type = tr.getApiType(name)
                    if type == if_type:
                        res_time_list = []
                        uptm_list = []
                        for j in data:
                            if j['if_name'] == name:
                                res_time_list.append(j['res_time'])
                                uptm_list.append(j['uptm'])

                        res_time_list_thousand = [x*1000 for x in res_time_list]
                        all_res_time[name] = res_time_list_thousand

                        all_uptm[name] = uptm_list
        return all_res_time, all_uptm
コード例 #8
0
ファイル: Main.py プロジェクト: betaros/traffic_sign
 def __init__(self):
     """
     Initialization
     """
     self.misc = Misc()
     self.recognition = Recognition()
     self.training = Training()
コード例 #9
0
        def initUI(self):

            # Add the widgets
            self._setup = Setup()
            self._negf_para = Negf_para()
            self._species = species()
            self._misc = Misc()
            self._grids = Grids()
            self._mdscf = Mdscf()
            self._io = IOcontrol()
            self._configuration = Configuration()
            self._default_input = default_input_para()

            #self._widgets = [self._setup, self._misc, self._mdscf, self._io,
            #                 self._species, self._grids, self._default_input,
            #                 self._configuration, self._negf_para]
            self._widgets = [
                self._setup, self._misc, self._mdscf, self._io, self._species,
                self._grids, self._default_input, self._negf_para
            ]
            # Main layout
            #layout = QtGui.QVBoxLayout()
            layout = QtGui.QGridLayout()
            layout.setSpacing(10)
            self.setLayout(layout)

            # Setup Groupbox
            savebtn = QtGui.QPushButton('Save')
            self.savedir = QtGui.QLineEdit(os.getcwd())
            choosedir = QtGui.QPushButton('...')
            choosedir.clicked.connect(self.selectdir)
            savebtn.clicked.connect(self.save)

            layout.addWidget(savebtn, 1, 0, 1, 1)
            layout.addWidget(self.savedir, 1, 1, 1, 4)
            layout.addWidget(choosedir, 1, 5, 1, 1)

            form_layout = QtGui.QTabWidget()
            layout.addWidget(form_layout, 2, 0, 1, 10)

            #form_layout = QtGui.QTabWidget(group_box)

            form_layout.addTab(self._setup, self.tr('Setup'))
            form_layout.addTab(self._mdscf, self.tr('MD SCF'))
            form_layout.addTab(self._grids, self.tr('Grids'))
            form_layout.addTab(self._negf_para, self.tr('NEGFctrl'))
            form_layout.addTab(self._species, self.tr('Species'))
            form_layout.addTab(self._misc, self.tr('Misc'))
            form_layout.addTab(self._io, self.tr('IO'))
            form_layout.addTab(self._configuration, self.tr('Configuration'))

            form_layout.currentChanged.connect(self.configurationChanged)
            #            self.connect(form_layout, QtCore.SIGNAL("currenChanged(int)"), self.configurationChanged)

            self.setGeometry(2000, 2000, 750, 750)
            self.setWindowTitle('NCSU RMG-NEGF GUI')
            self.show()
コード例 #10
0
ファイル: Training.py プロジェクト: betaros/traffic_sign
    def load_training_image_properties(self):
        """
        Loads training images properties
        :return:
        """
        iterator_training = Misc.folder_counter(self.training_path)
        image_list = []

        for i in range(0, iterator_training):
            class_number = Misc.fill_number(i, 5)
            training_path_class = os.path.join(self.training_path,
                                               class_number)
            csv_data = None
            for file in os.listdir(training_path_class):
                if file.endswith(".csv"):
                    csv_path = os.path.join(training_path_class, file)
                    csv_data = pd.read_csv(filepath_or_buffer=csv_path,
                                           sep=';')
                    # self.misc.logger.debug("CSV path: %s", csv_path)
                    break
            image_list.append(csv_data)
        return image_list
コード例 #11
0
ファイル: ApiMethod.py プロジェクト: xcma/selenium
    def getInterface_requests_status(cls, parmeter={}, headers={}, path='/index.php', method='GET', data={}):
        """
        requests接口访问
        :param parmeter:
        :param headers:
        :param path:
        :param method:
        :return:
        """
        url = main_domain+path

        try:
            start = Misc.getTimeStamp()
            response = requests.request(method, url, headers=headers, params=parmeter, data=data)
            end = Misc.getTimeStamp()
            res_time = Misc.getTime(start,end)
            Api_urllib.save_as_file(res_time, 'res_time', 'w')
            try:
                log.debug(response.text)
            except:
                log.debug(response.json())
            status_code = response.status_code

            log.debug('status:%s' % status_code)
            if Api_urllib.get_status_code(status_code):
                try:
                    return response.json(), status_code
                except:
                    return response.text, status_code
            else:
                return "Error", status_code

        except Exception as msg:
            log.error(msg)
            print (msg)
            raise
コード例 #12
0
ファイル: Training.py プロジェクト: betaros/traffic_sign
class Training:
    """
    Training class
    """
    def __init__(self):
        """
        Initialising
        """
        self.misc = Misc()
        self.training_path = os.path.join(self.misc.project_root, "dataset",
                                          "GTSRB", "Final_Training", "Images")
        self.test_path = os.path.join(self.misc.project_root, "dataset",
                                      "GTSRB", "Final_Test", "Images")

    def download_pos_files(self, images=True, haar=False):
        """
        Downloads and extracts the datasets selected
        :param images:
        :param haar:
        :return:
        """
        url = "http://benchmark.ini.rub.de/Dataset/"

        file_list = [
            "GTSRB_Final_Training_Images.zip", "GTSRB_Final_Test_Images.zip",
            "GTSRB_Final_Training_Haar.zip", "GTSRB_Final_Test_Haar.zip"
        ]

        for file in file_list:
            name_split = file.split("_")
            name_split[3] = name_split[3][:-4]
            folder_path = os.path.join(self.misc.project_root, "dataset",
                                       name_split[0],
                                       "_".join(name_split[1:3]),
                                       name_split[3])

            haar2 = haar and name_split[3] == "Haar"
            images2 = images and name_split[3] == "Images"

            if os.path.exists(folder_path) and (haar2 or images2):
                self.misc.logger.debug("Skip downloading %s", file)
                continue

            link = url + file
            store = os.path.join(self.misc.project_root, file)
            extract_path = os.path.join(self.misc.project_root, "dataset")

            if not os.path.isfile(store):
                try:
                    self.misc.logger.debug("Downloading files to %s", store)
                    urllib.request.urlretrieve(link, store)
                    self.misc.logger.debug("Finished downloading")
                except (urllib.request.HTTPError, urllib.request.URLError):
                    self.misc.logger.error("Unable to download data")

                try:
                    zf = zipfile.ZipFile(store)
                    self.misc.logger.debug("Extracting %s", file)
                    zf.extractall(path=extract_path)
                    self.misc.logger.debug("Extraction complete")
                    zf.close()

                    os.remove(store)
                except (ValueError, RuntimeError):
                    self.misc.logger.error("Unable to extract data")
            else:
                self.misc.logger.debug("Skip downloading %s", file)

    def download_neg_files(self):
        """
        Downloading negative sample files

        Source: http://www.robots.ox.ac.uk/~vgg/data/bicos/
        """
        url = "http://www.robots.ox.ac.uk/~vgg/data/bicos/data/"
        file = "airplanes.tar"

        link = os.path.join(url, file)
        store = os.path.join(self.misc.project_root, file)
        extract_path = os.path.join(self.misc.project_root, "dataset")

        if os.path.exists(os.path.join(extract_path, "airplanes")):
            self.misc.logger.debug("Skip downloading %s", file)
            return

        if not os.path.isfile(store):
            try:
                self.misc.logger.debug("Downloading files to %s", store)
                urllib.request.urlretrieve(link, store)
                self.misc.logger.debug("Finished downloading")
            except (urllib.request.HTTPError, urllib.request.URLError):
                self.misc.logger.error("Unable to download data")

            try:
                self.misc.logger.debug("Extracting %s", file)
                with tarfile.open(store) as tar:
                    subdir_and_files = [
                        tarinfo for tarinfo in tar.getmembers()
                        if tarinfo.name.startswith("airplanes/jpg/")
                    ]
                    tar.extractall(members=subdir_and_files, path=extract_path)
                self.misc.logger.debug("Extraction complete")
                os.remove(store)
            except (ValueError, RuntimeError):
                self.misc.logger.error("Unable to extract data")
        else:
            self.misc.logger.debug("Skip downloading %s", file)

    def download_face_recognition_haar(self):
        """
        Downloading face recognition haar data as sample data
        :return:
        """
        link = "https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_default.xml"
        store = os.path.join(self.misc.project_root, "dataset",
                             "haarcascade_frontalface_default.xml")

        if not os.path.isfile(store):
            try:
                self.misc.logger.debug("Downloading files to %s", store)
                urllib.request.urlretrieve(link, store)
                self.misc.logger.debug("Finished downloading")
            except (urllib.request.HTTPError, urllib.request.URLError):
                self.misc.logger.error("Unable to download data")
        else:
            self.misc.logger.debug(
                "Skip downloading haarcascade_frontalface_default.xml")

    def manipulate_image(self):
        """
        Modifies images to gray scale and resize it
        :return:
        """
        gtsrb_exists = False
        neg_exists = False
        traffic_exists = False

        # Walk through datasets and manipulate images
        for (dir_path, dir_names, file_names) in os.walk(
                os.path.join(self.misc.project_root, "dataset")):
            for dir_name in dir_names:
                # Create mod dir if not exists
                if dir_name == "Images":
                    image_mod_path = os.path.join(dir_path, "Images_mod")
                    if not os.path.exists(image_mod_path):
                        os.mkdir(image_mod_path)
                        self.misc.logger.debug("Created folder %s",
                                               image_mod_path)
                    else:
                        gtsrb_exists = True
                        self.misc.logger.debug(
                            "Skip manipulating positive images")
                if dir_name == "jpg":
                    jpg_mod_path = os.path.join(dir_path, "jpg_mod")
                    if not os.path.exists(jpg_mod_path):
                        os.mkdir(jpg_mod_path)
                        self.misc.logger.debug("Created folder %s",
                                               jpg_mod_path)
                    else:
                        neg_exists = True
                        self.misc.logger.debug(
                            "Skip manipulating negative images")
                if dir_name == "traffic":
                    traffic_mod_path = os.path.join(dir_path, "traffic_mod")
                    if not os.path.exists(traffic_mod_path):
                        os.mkdir(traffic_mod_path)
                        self.misc.logger.debug("Created folder %s",
                                               traffic_mod_path)
                    else:
                        traffic_exists = True
                        self.misc.logger.debug(
                            "Skip manipulating positive images")

            # manipulate files
            for file_name in file_names:
                if file_name.endswith(".ppm") and "Image" in dir_path:
                    if gtsrb_exists:
                        continue

                    img = cv2.imread(os.path.join(dir_path, file_name),
                                     cv2.IMREAD_GRAYSCALE)
                    dim = 50
                    resized_image = cv2.resize(img, (dim, dim))
                    resized_image = cv2.cvtColor(resized_image,
                                                 cv2.COLOR_GRAY2BGR)

                    try:
                        dir_path_mod = os.path.join(dir_path[:-16],
                                                    "Images_mod",
                                                    dir_path[-5:])
                        if not os.path.exists(dir_path_mod):
                            os.mkdir(dir_path_mod)
                            self.misc.logger.debug("Created folder %s",
                                                   dir_path_mod)
                    except ValueError:
                        dir_path_mod = os.path.join(dir_path[:-16],
                                                    "Images_mod")
                    store_path = os.path.join(dir_path_mod, file_name)
                    cv2.imwrite(store_path, resized_image)
                if file_name.endswith(".jpg") and "airplanes" in dir_path:
                    if neg_exists:
                        continue

                    img = cv2.imread(os.path.join(dir_path, file_name),
                                     cv2.IMREAD_GRAYSCALE)
                    dim = 100
                    resized_image = cv2.resize(img, (dim, dim))
                    resized_image = cv2.cvtColor(resized_image,
                                                 cv2.COLOR_GRAY2BGR)
                    dir_path_mod = os.path.join(dir_path[:-3], "jpg_mod")

                    store_path = os.path.join(dir_path_mod, file_name)
                    cv2.imwrite(store_path, resized_image)
                if file_name.endswith(".jpg") and "traffic" in dir_path:
                    if traffic_exists:
                        continue

                    img = cv2.imread(os.path.join(dir_path, file_name),
                                     cv2.IMREAD_GRAYSCALE)
                    dim = 50
                    resized_image = cv2.resize(img, (dim, dim))
                    resized_image = cv2.cvtColor(resized_image,
                                                 cv2.COLOR_GRAY2BGR)

                    try:
                        dir_path_mod = os.path.join(dir_path[:-10],
                                                    "traffic_mod",
                                                    dir_path[-2:])
                        if not os.path.exists(dir_path_mod):
                            os.mkdir(dir_path_mod)
                            self.misc.logger.debug("Created folder %s",
                                                   dir_path_mod)
                    except ValueError:
                        dir_path_mod = os.path.join(dir_path[:-10],
                                                    "traffic_mod")
                    store_path = os.path.join(dir_path_mod, file_name)
                    cv2.imwrite(store_path, resized_image)

    def generate_description_gtsrb(self):
        """

        :return:
        """
        class_id = 0

        training_properties = self.load_training_image_properties()
        info_file_path = os.path.join(self.misc.project_root, "info.dat")
        if os.path.isfile(info_file_path):
            os.remove(info_file_path)

        for element in training_properties:
            for index, row in element.iterrows():
                if row['ClassId'] > class_id:
                    class_id = row['ClassId']
                line = os.path.join(self.misc.project_root, "dataset", "GTSRB", "Final_Training", "Images_mod",
                                    self.misc.fill_number(row['ClassId'], 5), row['Filename']) \
                                    + ' 1 ' + str(self.misc.interpolate(row['Roi.X1'], 0, row['Width'], 0, 50)) \
                                    + ' ' + str(self.misc.interpolate(row['Roi.Y1'], 0, row['Height'], 0, 50)) \
                                    + ' ' + str(self.misc.interpolate(row['Roi.X2'] - row['Roi.X1'], 0, row['Width'], 0, 50)) \
                                    + ' ' + str(self.misc.interpolate(row['Roi.Y2'] - row['Roi.Y1'], 0, row['Height'], 0, 50)) + '\n'
                with open(info_file_path, 'a') as f:
                    f.write(line)

                # line = os.path.join(self.misc.project_root, "dataset", "GTSRB", "Final_Training", row['Filename'])
                # with open('bg.txt', 'a') as f:
                #    f.write(line)

    def generate_description_traffic(self):
        """

        :return:
        """
        self.misc.logger.debug("Generate description for traffic dataset")
        root_dir = os.path.join(self.misc.project_root, "dataset",
                                "traffic_mod")
        for dir_name, subdir_list, file_list in os.walk(root_dir):
            if subdir_list:
                for element in subdir_list:
                    info_path = os.path.join(root_dir, element, "info.dat")
                    if os.path.isfile(info_path):
                        self.misc.logger.debug("info.dat already exists")
                        return
            for fname in file_list:
                line = os.path.join(root_dir, dir_name, fname) + " 1 0 0 50 50"
                # self.misc.logger.debug(line)

                with open(os.path.join(root_dir, dir_name, "info.dat"),
                          'a') as f:
                    line = line + "\n"
                    f.write(line)

    def generate_description_airplanes(self):
        """

        :return:
        """
        self.misc.logger.debug("Generate description for airplanes dataset")
        root_dir = os.path.join(self.misc.project_root, "dataset", "airplanes",
                                "jpg_mod")
        for dir_name, subdir_list, file_list in os.walk(root_dir):
            info_path = os.path.join(root_dir, "bg.txt")
            if os.path.isfile(info_path):
                self.misc.logger.debug("info.dat already exists")
                return
            for fname in file_list:
                line = os.path.join(root_dir, fname)
                # self.misc.logger.debug(line)

                with open(os.path.join(root_dir, dir_name, "bg.txt"),
                          'a') as f:
                    line = line + "\n"
                    f.write(line)

    def load_training_image_properties(self):
        """
        Loads training images properties
        :return:
        """
        iterator_training = Misc.folder_counter(self.training_path)
        image_list = []

        for i in range(0, iterator_training):
            class_number = Misc.fill_number(i, 5)
            training_path_class = os.path.join(self.training_path,
                                               class_number)
            csv_data = None
            for file in os.listdir(training_path_class):
                if file.endswith(".csv"):
                    csv_path = os.path.join(training_path_class, file)
                    csv_data = pd.read_csv(filepath_or_buffer=csv_path,
                                           sep=';')
                    # self.misc.logger.debug("CSV path: %s", csv_path)
                    break
            image_list.append(csv_data)
        return image_list

    def load_test_image_properties(self):
        """
        Loads test images properties
        :return:
        """
        image_list = []
        csv_data = None
        for file in os.listdir(self.test_path):
            if file.endswith(".csv"):
                csv_path = os.path.join(self.test_path, file)
                csv_data = pd.read_csv(csv_path)
                # self.misc.logger.debug("CSV path: %s", csv_path)
                break
        image_list.append(csv_data)
        return image_list

    def load_images(self, training):
        """
        Load images from datasets
        :param training:
        :return:
        """
        if training:
            self.misc.logger.debug("Training set")
            image_list = self.load_training_image_properties()
        else:
            self.misc.logger.debug("Test set")
            image_list = self.load_training_image_properties()

        for element in image_list:
            self.misc.logger.debug("Class id: %i", element["ClassId"][0])
            for index, row in element.iterrows():
                img_path = os.path.join(self.training_path,
                                        Misc().fill_number(row['ClassId'], 5),
                                        row['Filename'])
                # if index == 0:
                # self.show(img_path, row['Roi.X1'], row['Roi.Y1'], row['Roi.X2'], row['Roi.Y2'])
                self.misc.logger.debug(
                    str(row['ClassId']) + " " + row['Filename'] + " " +
                    str(row['Height']) + " " + str(row['Width']) + " " +
                    str(row['Roi.X1']) + " " + str(row['Roi.Y1']) + " " +
                    str(row['Roi.X2']) + " " + str(row['Roi.Y2']))
        return None
コード例 #13
0
 def __init__(self):
     self.voiceh = SpeechInterface()
     self.misc = Misc()
コード例 #14
0
 def extract_one_word_cat(str_list):
     if len(str_list) == 0:
         return ''
     else:
         return Misc.extract_first_word(str_list[0])
コード例 #15
0
 def get_spoken_text(self):
     temp = []
     for i in self.results:
         temp.append(Misc.get_string(i, Hook.Actor_SpokenText))
     return temp
コード例 #16
0
 def __init__(self):
     """
     Initialising
     """
     self.misc = Misc()
コード例 #17
0
 def get_name(self):
     temp = []
     for i in self.get_id():
         temp.append(Misc.get_cache_entry(i, 'name', 'npc'))
     return temp
コード例 #18
0
class CommandHandler:
    def __init__(self):
        self.voiceh = SpeechInterface()
        self.misc = Misc()

    """ Software shortcuts """

    def open_firefox(self, *args, **kwargs):
        firefox_root = "C:\\Program Files\\Mozilla Firefox"
        # If no sub url specified, just open firefox
        if not args:
            self.misc.open_program(directory=firefox_root,
                                   executable="firefox.exe")
        else:
            # Otherwise attempt a search on multiple domain extension, if a site without 400+ error is found set as url
            parsed_url = None
            for i in ["be", "com", "nl", "org", "co"]:
                current_url = "http://www.%s.%s" % ("".join(
                    args[0]).lower(), i)
                try:
                    header = httplib2.Http()
                    response = header.request(current_url, "HEAD")
                    if int(response[0]["status"]) < 400:
                        parsed_url = current_url
                except Exception:
                    continue
                finally:
                    if parsed_url:
                        break

            # Open firefox with parsed url if a valid site has been found
            self.misc.open_program(directory=firefox_root, executable="firefox.exe %s" % parsed_url) if parsed_url else\
                self.voiceh.speak("Unable to find correct url.")

    def open_partitions(self):
        self.misc.open_program("diskmgmt.msc")

    def open_notepad(self):
        self.misc.open_program("notepad.exe")

    def open_calculator(self):
        self.misc.open_program("calc")

    def open_terminal(self):
        self.misc.open_program("start cmd.exe")

    """ Power control """

    def sleep(self):
        self.misc.open_program(
            "rundll32.exe powrprof.dll,SetSuspendState 0,1,0")

    def shutdown(self):
        self.misc.open_program("shutdown.exe -s -t 0")

    def restart(self):
        self.misc.open_program("shutdown -r -t 5")

    """ Software Control """

    def play_music(self, play=True):
        if self.misc.window_exists("spotify"):
            self.misc.focus_window("spotify")
        else:
            self.misc.open_program(executable="spotify.exe")

        time.sleep(5)
        if play:
            self.misc.search_screen(image="assets/images/spotify_play.png",
                                    click_center=True)

    def next_song(self):
        if self.misc.window_exists("spotify"):
            self.misc.focus_window("spotify")
        else:
            self.play_music(play=False)

        time.sleep(1)
        self.misc.search_screen(image="assets/images/next_song.png",
                                click_center=True)

    def previous_song(self):
        if self.misc.window_exists("spotify"):
            self.misc.focus_window("spotify")
        else:
            self.play_music(play=False)

        time.sleep(1)
        self.misc.search_screen(image="assets/images/previous_song.png",
                                click_center=True)

    def stop_music(self):
        self.misc.open_program("taskkill /f /im spotify.exe")

    def play_song(self, *args, **kwargs):
        client_id = ""
        client_secret = ""

        # Connecting to the api
        def connect_to_spotify():
            client_credentials_manager = SpotifyClientCredentials(
                client_id=client_id, client_secret=client_secret)
            sp = spotipy.Spotify(
                client_credentials_manager=client_credentials_manager)
            return sp

        # Searching track based on search query.
        def search_track(search_query: str):
            conn = connect_to_spotify()
            result = conn.search(search_query, type="track")
            found_songs = {}
            for set in result["tracks"]["items"]:
                found_songs[set["name"].lower()] = set["uri"]
            return found_songs

        # If a valid client id & secret has been set attempt to scrape track.
        if client_id and client_secret:
            songs = search_track(args[0])
            self.misc.open_program("start {}".format(
                songs.get(list(songs.keys())[0])))
            self.misc.focus_window("spotify")
            time.sleep(0.5)
            self.misc.search_screen(image="assets/images/highlighted_song.png",
                                    click_center=True)
        else:  # Otherwise give the url to create a developer application.
            self.voiceh.speak(
                "No developer application set, please follow the guide on the logged link in terminal"
            )
            self.voiceh.speak(
                "Afterwards set the client id/secret in play song function")
            print(
                "https://developer.spotify.com/documentation/general/guides/app-settings/?fbclid=IwAR1xHP62ZxxsI2GqAibc0tE5EPEUv0_G_uAkPoMQODtJz_il8tEsJbX5P0c#register-your-app"
            )

    """ Miscellaneous """

    def tell_me_a_joke(self):
        print("Telling a joke")
        # Fetch jokes from API
        url = "https://official-joke-api.appspot.com/random_ten"
        url_response = eval(requests.get(url).text)
        random_joke = random.choice(url_response)
        self.voiceh.speak(random_joke["setup"])
        self.voiceh.speak(random_joke["punchline"])

    def movie_suggestion(self, *args, **kwargs):
        def scrape_movie_list(genre):
            # if a genre has been set, scrape list from IMDB
            page = requests.get(
                "https://www.imdb.com/search/title/?genres={genre}".format(
                    genre=genre))
            soupobj = bs4.BeautifulSoup(page.text, features="html.parser")
            raw_movie_list = soupobj.find_all("div",
                                              class_="lister-item-content")

            movies = {}
            # Loop through all movies & get title & description from each movie.
            for movie in raw_movie_list:
                subsoup = bs4.BeautifulSoup(str(movie), features="html.parser")
                title = [
                    i for i in subsoup.find_all("a")
                    if "title/tt" in str(i) and not "vote" in str(i)
                ][0]
                title = str(title)[str(title).find('">') +
                                   2:str(title).find('</')]

                for indx, i in enumerate(
                        subsoup.find_all("p", class_="text-muted")):
                    if indx != 1:
                        continue
                    description = str(i)[str(i).find("\n") +
                                         1:str(i).find("</p")].strip()
                    movies[title] = description
            return movies

        def get_genre(search_str=None):
            genre = [
                "horror", "action", "sci-fi", "thriller", "crime", "mystery"
            ]
            if search_str:
                search = self.misc.stringset_comparer(search_str, genre)
                if search:
                    return search
                else:
                    return
            else:
                return random.choice(genre)

        genre = get_genre(args[0]) if args else get_genre()
        if genre:
            movies = scrape_movie_list(genre)

            # Select a random movie from dictionairy
            random_movie = random.choice(list(movies.keys()))
            self.voiceh.speak(random_movie)
            self.voiceh.speak(movies[random_movie])

            # Print in terminal if something wasnt audible given the option to read it:
            print("Name: %s\nDescription: %s" %
                  (random_movie, movies[random_movie]))
            time.sleep(
                1
            )  # Add sleep otherwise, command question was to fast / unatural.

    def commands(self):
        self.voiceh.speak("Voice commands are: ")
        for i in [
                k for k in list(self.__class__.__dict__.keys())
                if "__" not in k
        ]:
            i = i if not "_" in i else i.replace("_", " ")
            self.voiceh.speak(i)