Python config.load() Examples

The following are 9 code examples of config.load(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module config , or try the search function .
Example #1
Source File: web_control.py    From oss-ftp with MIT License 6 votes vote down vote up
def load_module_menus(self):
        global module_menus
        module_menus = {}
        #config.load()
        modules = config.get(['modules'], None)
        for module in modules:
            values = modules[module]
            if module != "launcher" and config.get(["modules", module, "auto_start"], 0) != 1:
                continue

            #version = values["current_version"]
            menu_path = os.path.join(root_path, module, "web_ui", "menu.json")
            if not os.path.isfile(menu_path):
                continue
                
            module_menu = json.load(file(menu_path, 'r'))          
            module_menus[module] = module_menu

        module_menus = sorted(module_menus.iteritems(), key=lambda (k,v): (v['menu_sort_id']))
        #for k,v in self.module_menus:
        #    logging.debug("m:%s id:%d", k, v['menu_sort_id']) 
Example #2
Source File: web_control.py    From oss-ftp with MIT License 6 votes vote down vote up
def req_init_module_handler(self):
        req = urlparse.urlparse(self.path).query
        reqs = urlparse.parse_qs(req, keep_blank_values=True)
        data = ''

        try:
            module = reqs['module'][0]
            config.load()

            if reqs['cmd'] == ['start']:
                result = module_init.start(module)
                data = '{ "module": "%s", "cmd": "start", "result": "%s" }' % (module, result)
            elif reqs['cmd'] == ['stop']:
                result = module_init.stop(module)
                data = '{ "module": "%s", "cmd": "stop", "result": "%s" }' % (module, result)
            elif reqs['cmd'] == ['restart']:
                result_stop = module_init.stop(module)
                result_start = module_init.start(module)
                data = '{ "module": "%s", "cmd": "restart", "stop_result": "%s", "start_result": "%s" }' % (module, result_stop, result_start)
        except Exception as e:
            launcher_log.exception("init_module except:%s", e)

        self.send_response("text/html", data) 
Example #3
Source File: prepare_seg_tri_dataset.py    From portrait_matting with GNU General Public License v3.0 6 votes vote down vote up
def main():
    # Argument
    parser = argparse.ArgumentParser(description='Dataset Preparing Script')
    parser.add_argument('--config', '-c', default='config.json',
                        help='Load config from given json file')
    args = parser.parse_args()

    # Load config
    config.load(args.config)

    # Get valid names for alpha matting
    names = get_valid_names(config.img_crop_dir, config.img_mask_dir,
                            config.img_mean_mask_dir, config.img_mean_grid_dir,
                            config.img_alpha_dir,
                            rm_exts=[False, False, False, True, False])

    # Compute trimap
    logger.info('Compute weight matrix for each image')
    os.makedirs(config.img_trimap_dir, exist_ok=True)
    for name in names:
        compute_trimap_from_alpha(name, config.img_alpha_dir,
                                  config.img_trimap_dir) 
Example #4
Source File: core.py    From forge with Apache License 2.0 5 votes vote down vote up
def load_config(self):
        if not self.config:
            raise TaskError("unable to find forge.yaml, try running `forge setup`")

        try:
            conf = config.load(self.config)
        except config.SchemaError, e:
            raise TaskError(str(e)) 
Example #5
Source File: prepare_seg_dataset.py    From portrait_matting with GNU General Public License v3.0 5 votes vote down vote up
def main():
    # Argument
    parser = argparse.ArgumentParser(description='Dataset Preparing Script')
    parser.add_argument('--config', '-c', default='config.json',
                        help='Load config from given json file')
    args = parser.parse_args()

    # Load config
    config.load(args.config)

    # Load image urls
    url_pairs = load_img_urls(config.org_imgurl_filepath)
    # Download
    os.makedirs(config.img_raw_dir, exist_ok=True)
    for name, url in url_pairs:
        download_img(url, name, config.img_raw_dir)

    # Load crop rectangles
    rect_pairs = load_crop_rects(config.org_crop_filepath)
    # Crop
    img_size = (600, 800)  # Decided by mask size
    os.makedirs(config.img_crop_dir, exist_ok=True)
    for name, rect in rect_pairs:
        crop_img(name, config.img_raw_dir, config.img_crop_dir, rect, img_size)

    # Parse masks
    os.makedirs(config.img_mask_dir, exist_ok=True)
    for name, _ in rect_pairs:
        mask_name = '{}_mask.mat'.format(os.path.splitext(name)[0])
        parse_mask(mask_name, config.org_mask_dir, name, config.img_mask_dir) 
Example #6
Source File: prepare_seg_plus_dataset.py    From portrait_matting with GNU General Public License v3.0 5 votes vote down vote up
def main():
    # Argument
    parser = argparse.ArgumentParser(description='Dataset Preparing Script')
    parser.add_argument('--config', '-c', default='config.json',
                        help='Load config from given json file')
    args = parser.parse_args()

    # Load config
    config.load(args.config)

    # Setup segmentation dataset
    dataset = PortraitSegDataset(config.img_crop_dir, config.img_mask_dir)
    # Split into train and test
    train_raw, _ = split_dataset(dataset)

    # Setup mean mask
    face_masker = FaceMasker(config.face_predictor_filepath,
                             config.mean_mask_filepath, train_raw)

    # Get valid names in 3 channel segmentation stage
    names = get_valid_names(config.img_crop_dir, config.img_mask_dir)

    # Start alignment
    logger.info('Generate aligned mask and grids')
    os.makedirs(config.img_mean_mask_dir, exist_ok=True)
    os.makedirs(config.img_mean_grid_dir, exist_ok=True)
    for name in names:
        align_mask(name, config.img_crop_dir, config.img_mean_mask_dir,
                   config.img_mean_grid_dir, face_masker) 
Example #7
Source File: prepare_matting_dataset.py    From portrait_matting with GNU General Public License v3.0 5 votes vote down vote up
def main():
    # Argument
    parser = argparse.ArgumentParser(description='Dataset Preparing Script')
    parser.add_argument('--config', '-c', default='config.json',
                        help='Load config from given json file')
    parser.add_argument('--pseudo_alpha', action='store_true',
                        help='Dummy alpha generation')
    args = parser.parse_args()

    # Load config
    config.load(args.config)

    if args.pseudo_alpha:
        logger.info('Compute pseudo alpha images')
        # Get valid names in 6 channel segmentation stage
        names = get_valid_names(config.img_crop_dir, config.img_mask_dir,
                                config.img_mean_mask_dir,
                                config.img_mean_grid_dir,
                                rm_exts=[False, False, False, True])
        # Create pseudo alpha images
        os.makedirs(config.img_alpha_dir, exist_ok=True)
        for name in names:
            create_pseudo_alpha(name, config.img_mask_dir,
                                config.img_alpha_dir)

    # Get valid names for alpha matting
    names = get_valid_names(config.img_crop_dir, config.img_mask_dir,
                            config.img_mean_mask_dir, config.img_mean_grid_dir,
                            config.img_alpha_dir,
                            rm_exts=[False, False, False, True, False])

    # Pre-compute look up table for weights
    logger.info('Compute look up table for weights')
    weight_lut = AlphaWeightLut(names, config.img_alpha_dir)

    # Compute weight matrix
    logger.info('Compute weight matrix for each image')
    os.makedirs(config.img_alpha_weight_dir, exist_ok=True)
    for name in names:
        compute_weights(name, config.img_alpha_dir,
                        config.img_alpha_weight_dir, weight_lut) 
Example #8
Source File: index.py    From rep0st with MIT License 5 votes vote down vote up
def load_index(self, index_id):
        if self.annoy_index is None:
            log.info("loading initial index with id {}", self.current_index)
        else:
            log.info("switching index from {} to {}", self.current_index, index_id)

        newindex = AnnoyIndex(108, metric='euclidean')
        newindex.load(config.index_config['index_path'] + 'index_' + str(index_id) + '.ann')
        if self.annoy_index is not None:
            self.annoy_index.unload()
        self.annoy_index = newindex
        self.current_index = index_id
        log.info("finished switching index. now using index {}", self.current_index) 
Example #9
Source File: test.py    From portrait_matting with GNU General Public License v3.0 4 votes vote down vote up
def main(argv):
    # Argument
    parser = argparse.ArgumentParser(description='Dataset Preparing Script')
    parser.add_argument('--config', '-c', default='config.json',
                        help='Load config from given json file')
    parser.add_argument('-i', required=True,
                        help='Input image file path')
    parser.add_argument('-o', default='output.png',
                        help='Output image file path')
    parser.add_argument('--mode', choices=['seg', 'seg+', 'seg_tri', 'mat'],
                        help='Model mode', required=True)
    parser.add_argument('--model_path', required=True,
                        help='Pretrained model path')
    parser.add_argument('--model_mode', default=None,
                        help='Mode for loading `model_path`')
    parser.add_argument('--gpu', '-g', type=int, default=-1,
                        help='GPU ID (negative value indicates CPU)')
    args = parser.parse_args(argv)

    inp_filepath, out_filepath = args.i, args.o

    # Load config
    config.load(args.config)

    # Create predictor
    predictor = Predictor(args.mode, args.model_path, args.model_mode,
                          args.gpu, config.face_predictor_filepath,
                          config.mean_mask_filepath)

    # Load input image
    logger.info('Load input file: %s', inp_filepath)
    img = cv2.imread(inp_filepath)
    if img is None:
        logger.error('Failed to load')
        return

    # Predict
    ret = predictor.predict(img)
    if ret is None:
        logger.error('Failed to predict')
        return

    if args.mode.startswith('seg'):
        score = ret

        # Convert to trimap
        score = np.argmax(score, axis=0)

        # Write out trimap
        vis_img = np.zeros_like(img)
        vis_img[score == 1] = 127
        vis_img[score == 2] = 255
        cv2.imwrite(out_filepath, vis_img)

    elif args.mode.startswith('mat'):
        alpha = ret

        # Write out alpha
        cv2.imwrite(out_filepath, alpha * 255)