Exemplo n.º 1
0
def version():
    """ Show LS backend and LS frontend versions
    """
    with open(find_dir('static/editor') + '/version.json') as f:
        lsf = json.load(f)
    with open(find_dir('static/dm') + '/version.json') as f:
        dm = json.load(f)
    ver = {
        'label-studio-frontend': lsf,
        'label-studio-datamanager': dm,
        'label-studio-backend': label_studio.__version__
    }
    return make_response(jsonify(ver), 200)
Exemplo n.º 2
0
def create_dir(args):

    output_dir = os.path.join(args.root_dir, args.project_name)
    if os.path.exists(output_dir) and args.force:
        shutil.rmtree(output_dir)
    elif os.path.exists(output_dir):
        raise FileExistsError('Model directory already exists. Please remove it or use --force option.')

    default_configs_dir = find_dir('default_configs')
    shutil.copytree(default_configs_dir, output_dir, ignore=shutil.ignore_patterns('*.tmpl'))

    # extract script name and model class
    if not args.script:
        logger.warning('You don\'t specify script path: by default, "./model.py" is used')
        script_path = 'model.py'
    else:
        script_path = args.script

    def model_def_in_path(path):
        is_windows_path = path[1:].startswith(':\\')
        return ':' in path[2:] if is_windows_path else ':' in path

    if model_def_in_path(script_path):
        script_path, model_class = args.script.rsplit(':', 1)
    else:
        model_classes = get_all_classes_inherited_LabelStudioMLBase(script_path)
        if len(model_classes) > 1:
            raise ValueError(
                'You don\'t specify target model class, and we\'ve found {num} possible candidates within {script}. '
                'Please specify explicitly which one should be used using the following format:\n '
                '{script}:{model_class}'.format(num=len(model_classes), script=script_path, model_class=model_classes[0]))
        model_class = model_classes[0]

    if not os.path.exists(script_path):
        raise FileNotFoundError(script_path)

    def use(filename):
        filepath = os.path.join(os.path.dirname(script_path), filename)
        if os.path.exists(filepath):
            shutil.copy2(filepath, output_dir)

    script_base_name = os.path.basename(script_path)
    use(script_base_name)
    use('requirements.txt')
    use('README.md')

    wsgi_script_file = os.path.join(default_configs_dir, '_wsgi.py.tmpl')
    with open(wsgi_script_file) as f:
        wsgi_script = f.read()
    wsgi_script = wsgi_script.format(
        script=os.path.splitext(script_base_name)[0],
        model_class=model_class
    )
    wsgi_name = os.path.basename(wsgi_script_file).split('.tmpl', 1)[0]
    with open(os.path.join(output_dir, wsgi_name), mode='w') as fout:
        fout.write(wsgi_script)

    print(Fore.GREEN + 'Congratulations! ML Backend has been successfully initialized in ' + output_dir)
    print(Fore.RESET + 'Now start it by using:\n' + Fore.CYAN + 'label-studio-ml start ' + output_dir)
Exemplo n.º 3
0
def version():
    """Show backend and frontend version"""
    lsf = json.load(open(find_dir('static/editor') + '/version.json'))
    ver = {
        'label-studio-frontend': lsf,
        'label-studio-backend': label_studio.__version__
    }
    return make_response(jsonify(ver), 200)
Exemplo n.º 4
0
def version():
    """Show LS backend and LS frontend versions"""
    lsf = json.load(open(find_dir("static/editor") + "/version.json"))
    ver = {
        "label-studio-frontend": lsf,
        "label-studio-backend": label_studio.__version__,
    }
    return make_response(jsonify(ver), 200)
Exemplo n.º 5
0
def iter_config_templates():
    templates_dir = find_dir('examples')
    for d in os.listdir(templates_dir):
        # check xml config file exists
        path = os.path.join(templates_dir, d, 'config.xml')
        if not os.path.exists(path):
            continue
        yield path
Exemplo n.º 6
0
def create_dir(args):
    output_dir = os.path.join(args.root_dir, args.project_name)
    if os.path.exists(output_dir) and args.force:
        shutil.rmtree(output_dir)
    elif os.path.exists(output_dir):
        raise FileExistsError(
            'Model directory already exists. Please remove it or use --force option.'
        )

    default_configs_dir = find_dir('default_configs')
    shutil.copytree(default_configs_dir,
                    output_dir,
                    ignore=shutil.ignore_patterns('*.tmpl'))

    # extract script name and model class
    if not args.script:
        logger.warning(
            'You don\'t specify script path: by default, "./model.py" is used')
        script_path = 'model.py'
    else:
        script_path = args.script

    if not os.path.exists(script_path):
        raise FileNotFoundError(script_path)

    if ':' not in script_path:
        model_classes = get_all_classes_inherited_LabelStudioMLBase(
            script_path)
        if len(model_classes) > 1:
            raise ValueError(
                'You don\'t specify target model class, and we\'ve found {num} possible candidates within {script}. '
                'Please specify explicitly which one should be used using the following format:\n '
                '{script}:{model_class}'.format(num=len(model_classes),
                                                script=script_path,
                                                model_class=model_classes[0]))
        model_class = model_classes[0]
    else:
        script_path, model_class = args.script.split(':')

    script_base_name = os.path.basename(script_path)
    local_script_path = os.path.join(output_dir, os.path.basename(script_path))
    shutil.copy2(script_path, local_script_path)

    wsgi_script_file = os.path.join(default_configs_dir, '_wsgi.py.tmpl')
    with open(wsgi_script_file) as f:
        wsgi_script = f.read()
    wsgi_script = wsgi_script.format(
        script=os.path.splitext(script_base_name)[0], model_class=model_class)
    wsgi_name = os.path.basename(wsgi_script_file).split('.tmpl', 1)[0]
    with open(os.path.join(output_dir, wsgi_name), mode='w') as fout:
        fout.write(wsgi_script)
Exemplo n.º 7
0
def create_dir(args):
    output_dir = os.path.join(args.root_dir, args.project_name)

    default_configs_dir = find_dir('default_configs')
    shutil.copytree(default_configs_dir, output_dir)

    # extract script name and model class
    if not args.script:
        logger.warning(
            'You don\'t specify script path: by default, "./model.py" is used')
        script_path = 'model.py'
    else:
        script_path = args.script

    if ':' not in script_path:
        model_classes = get_all_classes_inherited_LabelStudioMLBase(
            script_path)
        if len(model_classes) > 1:
            raise ValueError(
                'You don\'t specify target model class, and we\'ve found {num} possible candidates within {script}. '
                'Please specify explicitly which one should be used using the following format:\n '
                '{script}:{model_class}'.format(num=len(model_classes),
                                                script=script_path,
                                                model_class=model_classes[0]))
        model_class = model_classes[0]
    else:
        script_path, model_class = args.script.split(':')

    script_base_name = os.path.basename(script_path)
    local_script_path = os.path.join(output_dir, os.path.basename(script_path))
    shutil.copy2(script_path, local_script_path)

    wsgi_script_file = os.path.join(output_dir, '_wsgi.py.tmpl')
    with open(wsgi_script_file) as f:
        wsgi_script = f.read()

    wsgi_script = wsgi_script.format(
        script=os.path.splitext(script_base_name)[0],
        model_class=model_class,
        model_dir=args.model_dir,
        port=args.port)
    with open(wsgi_script_file.split('.tmpl')[0], mode='w') as fout:
        fout.write(wsgi_script)
Exemplo n.º 8
0
def send_static(path):
    """ Static serving
    """
    static_dir = find_dir('static')
    return flask.send_from_directory(static_dir, path)
Exemplo n.º 9
0
def send_media(path):
    """ Static for label tool js and css
    """
    media_dir = find_dir('static/media')
    return flask.send_from_directory(media_dir, path)
Exemplo n.º 10
0
def parse_input_args():
    """ Combine args with json config

    :return: config dict
    """
    import sys
    import argparse

    if len(sys.argv) == 1:
        print('\nQuick start usage: label-studio start my_project --init\n')

    root_parser = argparse.ArgumentParser(add_help=False)
    root_parser.add_argument('-b',
                             '--no-browser',
                             dest='no_browser',
                             action='store_true',
                             help='Do not open browser at label studio start')
    root_parser.add_argument('-d',
                             '--debug',
                             dest='debug',
                             action='store_true',
                             help='Debug mode for Flask',
                             default=None)
    root_parser.add_argument('--root-dir',
                             dest='root_dir',
                             default='.',
                             help='Projects root directory')
    root_parser.add_argument('-v',
                             '--verbose',
                             dest='verbose',
                             action='store_true',
                             help='Increase output verbosity')

    parser = argparse.ArgumentParser(description='Label studio')

    subparsers = parser.add_subparsers(dest='command',
                                       help='Available commands')
    subparsers.required = True

    # init sub-command parser

    available_templates = [
        os.path.basename(os.path.dirname(f)) for f in iter_config_templates()
    ]

    parser_init = subparsers.add_parser('init',
                                        help='Initialize Label Studio',
                                        parents=[root_parser])
    parser_init.add_argument(
        'project_name',
        help='Path to directory where project state will be initialized')
    parser_init.add_argument('--template',
                             dest='template',
                             choices=available_templates,
                             help='Choose from predefined project templates')

    # start sub-command parser

    parser_start = subparsers.add_parser('start',
                                         help='Start Label Studio server',
                                         parents=[root_parser])
    parser_start.add_argument(
        'project_name',
        help='Path to directory where project state has been initialized')
    parser_start.add_argument(
        '--init',
        dest='init',
        action='store_true',
        help='Initialize if project is not initialized yet')
    parser_start.add_argument('--template',
                              dest='template',
                              choices=available_templates,
                              help='Choose from predefined project templates')
    parser_start.add_argument('-c',
                              '--config',
                              dest='config_path',
                              help='Server config')
    parser_start.add_argument('-l',
                              '--label-config',
                              dest='label_config',
                              default='',
                              help='Label config path')
    parser_start.add_argument(
        '-i',
        '--input-path',
        dest='input_path',
        default='',
        help='Input path to task file or directory with tasks')
    parser_start.add_argument('-o',
                              '--output-dir',
                              dest='output_dir',
                              default='',
                              help='Output directory for completions')
    parser_start.add_argument('-p',
                              '--port',
                              dest='port',
                              default=8200,
                              type=int,
                              help='Server port')
    parser_start.add_argument(
        '--make-session-projects',
        dest='make_session_projects',
        action='store_true',
        help='Create new project for each browser session')

    # start-multi-session sub-command parser

    parser_start_ms = subparsers.add_parser('start-multi-session',
                                            help='Start Label Studio server',
                                            parents=[root_parser])
    parser_start_ms.add_argument(
        '--template',
        dest='template',
        choices=available_templates,
        help='Choose from predefined project templates')
    parser_start_ms.add_argument('-c',
                                 '--config',
                                 dest='config_path',
                                 help='Server config')
    parser_start_ms.add_argument('-l',
                                 '--label-config',
                                 dest='label_config',
                                 default='',
                                 help='Label config path')
    parser_start_ms.add_argument(
        '-i',
        '--input-path',
        dest='input_path',
        default='',
        help='Input path to task file or directory with tasks')
    parser_start_ms.add_argument('-o',
                                 '--output-dir',
                                 dest='output_dir',
                                 default='',
                                 help='Output directory for completions')
    parser_start_ms.add_argument('-p',
                                 '--port',
                                 dest='port',
                                 default=8200,
                                 type=int,
                                 help='Server port')

    args = parser.parse_args()
    label_config_explicitly_specified = hasattr(
        args, 'label_config') and args.label_config
    if args.template and not label_config_explicitly_specified:
        args.label_config = os.path.join(find_dir('examples'), args.template,
                                         'config.xml')
    if not hasattr(args, 'label_config'):
        args.label_config = None
    return args
Exemplo n.º 11
0
def parse_input_args():
    """ Combine args with json config

    :return: config dict
    """
    import sys
    import argparse

    if len(sys.argv) == 1:
        print('\nQuick start usage: label-studio start my_project --init\n')

    available_templates = [
        os.path.basename(os.path.dirname(f)) for f in iter_config_templates()
    ]

    def valid_filepath(filepath):
        path = os.path.abspath(os.path.expanduser(filepath))
        if os.path.exists(path):
            return path
        raise FileNotFoundError(filepath)

    root_parser = argparse.ArgumentParser(add_help=False)
    root_parser.add_argument('-b',
                             '--no-browser',
                             dest='no_browser',
                             action='store_true',
                             help='Do not open browser at label studio start')
    root_parser.add_argument('-d',
                             '--debug',
                             dest='debug',
                             action='store_true',
                             help='Debug mode for Flask',
                             default=None)
    root_parser.add_argument('--force',
                             dest='force',
                             action='store_true',
                             help='Force creation new resources if exist')
    root_parser.add_argument('--root-dir',
                             dest='root_dir',
                             default='.',
                             help='Projects root directory')
    root_parser.add_argument('-v',
                             '--verbose',
                             dest='verbose',
                             action='store_true',
                             help='Increase output verbosity')
    root_parser.add_argument('--template',
                             dest='template',
                             choices=available_templates,
                             help='Choose from predefined project templates')
    root_parser.add_argument('-c',
                             '--config',
                             dest='config_path',
                             type=valid_filepath,
                             help='Server config')
    root_parser.add_argument('-l',
                             '--label-config',
                             dest='label_config',
                             type=valid_filepath,
                             help='Label config path')
    root_parser.add_argument(
        '-i',
        '--input-path',
        dest='input_path',
        type=valid_filepath,
        help='Input path to task file or directory with tasks')
    root_parser.add_argument(
        '--input-format',
        dest='input_format',
        choices=('json', 'json-dir', 'text', 'text-dir', 'image-dir',
                 'audio-dir'),
        default='json',
        help=
        'Input tasks format. Unless you are using "json" or "json-dir" format, --label-config option is required'
    )
    root_parser.add_argument('-o',
                             '--output-dir',
                             dest='output_dir',
                             type=valid_filepath,
                             help='Output directory for completions')
    root_parser.add_argument('--ml-backend-url',
                             dest='ml_backend_url',
                             help='Machine learning backend URL')
    root_parser.add_argument('--ml-backend-name',
                             dest='ml_backend_name',
                             help='Machine learning backend name')
    root_parser.add_argument('-p',
                             '--port',
                             dest='port',
                             default=8200,
                             type=int,
                             help='Server port')

    parser = argparse.ArgumentParser(description='Label studio')

    subparsers = parser.add_subparsers(dest='command',
                                       help='Available commands')
    subparsers.required = True

    # init sub-command parser

    parser_init = subparsers.add_parser('init',
                                        help='Initialize Label Studio',
                                        parents=[root_parser])
    parser_init.add_argument(
        'project_name',
        help='Path to directory where project state will be initialized')

    # start sub-command parser

    parser_start = subparsers.add_parser('start',
                                         help='Start Label Studio server',
                                         parents=[root_parser])
    parser_start.add_argument(
        'project_name',
        help='Path to directory where project state has been initialized')
    parser_start.add_argument(
        '--init',
        dest='init',
        action='store_true',
        help='Initialize if project is not initialized yet')

    # start-multi-session sub-command parser

    parser_start_ms = subparsers.add_parser('start-multi-session',
                                            help='Start Label Studio server',
                                            parents=[root_parser])

    args = parser.parse_args()
    if args.output_dir is not None:
        raise RuntimeError(
            '"--output-dir" option is deprecated and has no effect.\n'
            'All output results are saved to project_name/completions directory'
        )

    label_config_explicitly_specified = hasattr(
        args, 'label_config') and args.label_config
    if args.template and not label_config_explicitly_specified:
        args.label_config = os.path.join(find_dir('examples'), args.template,
                                         'config.xml')
    if not hasattr(args, 'label_config'):
        args.label_config = None
    return args
Exemplo n.º 12
0
def parse_input_args():
    """ Combine args with json config

    :return: config dict
    """
    import sys
    import argparse
    from label_studio.project import Project

    if len(sys.argv) == 1:
        print('\nQuick start usage: label-studio start my_project --init\n')

    available_templates = [
        os.path.basename(os.path.dirname(f)) for f in iter_config_templates()
    ]

    def valid_filepath(filepath):
        path = os.path.abspath(os.path.expanduser(filepath))
        if os.path.exists(path):
            return path
        raise FileNotFoundError(filepath)

    root_parser = argparse.ArgumentParser(add_help=False)
    root_parser.add_argument('--version',
                             dest='version',
                             action='store_true',
                             help='Show Label Studio version')
    root_parser.add_argument('-b',
                             '--no-browser',
                             dest='no_browser',
                             action='store_true',
                             help='Do not open browser at label studio start')
    root_parser.add_argument('-d',
                             '--debug',
                             dest='debug',
                             action='store_true',
                             help='Debug mode for Flask',
                             default=None)
    root_parser.add_argument('--force',
                             dest='force',
                             action='store_true',
                             help='Force overwrite existing files')
    root_parser.add_argument('--root-dir',
                             dest='root_dir',
                             default='.',
                             help='Project root directory')
    root_parser.add_argument('-v',
                             '--verbose',
                             dest='verbose',
                             action='store_true',
                             help='Increase output verbosity')
    root_parser.add_argument('--template',
                             dest='template',
                             choices=available_templates,
                             help='Choose from predefined project templates')
    root_parser.add_argument('-c',
                             '--config',
                             dest='config_path',
                             type=valid_filepath,
                             help='Server config')
    root_parser.add_argument('-l',
                             '--label-config',
                             dest='label_config',
                             type=valid_filepath,
                             help='Label config path')
    root_parser.add_argument(
        '-i',
        '--input-path',
        dest='input_path',
        type=valid_filepath,
        help='Input path for task file or directory with tasks')
    root_parser.add_argument('-s',
                             '--source',
                             dest='source',
                             choices=Project.get_available_source_storages(),
                             help='Source data storage type')
    root_parser.add_argument('--source-path',
                             dest='source_path',
                             help='Source bucket name')
    root_parser.add_argument('--source-params',
                             dest='source_params',
                             type=json.loads,
                             default={},
                             help='JSON string representing source parameters')
    root_parser.add_argument('-t',
                             '--target',
                             dest='target',
                             choices=Project.get_available_target_storages(),
                             help='Target data storage type')
    root_parser.add_argument('--target-path',
                             dest='target_path',
                             help='Target bucket name')
    root_parser.add_argument('--target-params',
                             dest='target_params',
                             type=json.loads,
                             default={},
                             help='JSON string representing target parameters')
    root_parser.add_argument(
        '--input-format',
        dest='input_format',
        choices=('json', 'json-dir', 'text', 'text-dir', 'image-dir',
                 'audio-dir'),
        default='json',
        help=
        'Input tasks format. Unless you are using "json" or "json-dir" format, --label-config option is required'
    )
    root_parser.add_argument(
        '-o',
        '--output-dir',
        dest='output_dir',
        type=valid_filepath,
        help='Output directory for completions (unless cloud storage is used)')
    root_parser.add_argument('--ml-backends',
                             dest='ml_backends',
                             nargs='+',
                             help='Machine learning backends URLs')
    root_parser.add_argument('--sampling',
                             dest='sampling',
                             choices=['sequential', 'uniform'],
                             default='sequential',
                             help='Sampling type that defines tasks order')
    root_parser.add_argument('--log-level',
                             dest='log_level',
                             choices=['DEBUG', 'INFO', 'WARNING', 'ERROR'],
                             default=None,
                             help='Logging level')
    root_parser.add_argument(
        '--host',
        dest='host',
        type=str,
        help=
        'Server hostname for LS internal usage like import task urls generation, sample task urls, etc. '
        'If you need to start server on localhost instead of 0.0.0.0, just make it "localhost". '
        'Otherwise web-server host will be 0.0.0.0 always independent of this parameter.'
    )
    root_parser.add_argument('--protocol',
                             dest='protocol',
                             type=str,
                             help='Web protocol http:// or https://')
    root_parser.add_argument('-p',
                             '--port',
                             dest='port',
                             type=int,
                             help='Server port')
    root_parser.add_argument('--cert',
                             dest='cert_file',
                             type=valid_filepath,
                             help='Certificate file for HTTPS (in PEM format)')
    root_parser.add_argument('--key',
                             dest='key_file',
                             type=valid_filepath,
                             help='Private key file for HTTPS (in PEM format)')
    root_parser.add_argument(
        '--allow-serving-local-files',
        dest='allow_serving_local_files',
        action='store_true',
        help=
        'Allow serving local files (Warning! use this option only for your local runs)'
    )
    root_parser.add_argument('--use-gevent',
                             dest='use_gevent',
                             action='store_true',
                             help='Use gevent for better concurrency',
                             default=False)

    parser = argparse.ArgumentParser(description='Label studio')

    subparsers = parser.add_subparsers(dest='command',
                                       help='Available commands')
    subparsers.required = True

    # init sub-command parser

    parser_version = subparsers.add_parser('version',
                                           help='Print version info',
                                           parents=[root_parser])

    parser_init = subparsers.add_parser('init',
                                        help='Initialize Label Studio',
                                        parents=[root_parser])
    parser_init.add_argument(
        'project_name',
        help='Path to directory where project state will be initialized')

    # start sub-command parser

    parser_start = subparsers.add_parser('start',
                                         help='Start Label Studio server',
                                         parents=[root_parser])
    parser_start.add_argument(
        'project_name',
        help='Path to directory where project state has been initialized')
    parser_start.add_argument(
        '--init',
        dest='init',
        action='store_true',
        help='Initialize if project is not initialized yet')
    parser_start.add_argument('--password',
                              dest='password',
                              default='',
                              help='Password for web access')
    parser_start.add_argument('--username',
                              dest='username',
                              default='',
                              help='Username for web access')

    # start-multi-session sub-command parser

    parser_start_ms = subparsers.add_parser('start-multi-session',
                                            help='Start Label Studio server',
                                            parents=[root_parser])

    args = parser.parse_args()

    # print version
    if args.version or args.command == 'version':
        from label_studio import __version__
        print('\nLabel Studio version:', __version__, '\n')

    if args.output_dir is not None:
        raise RuntimeError(
            '"--output-dir" option is deprecated and has no effect.\n'
            'All output results are saved to project_name/completions directory'
        )

    label_config_explicitly_specified = hasattr(
        args, 'label_config') and args.label_config
    if args.template and not label_config_explicitly_specified:
        args.label_config = os.path.join(find_dir('examples'), args.template,
                                         'config.xml')
    if not hasattr(args, 'label_config'):
        args.label_config = None
    return args
Exemplo n.º 13
0
def create_dir(args):

    output_dir = os.path.join(args.root_dir, args.project_name)
    if os.path.exists(output_dir) and args.force:
        shutil.rmtree(output_dir)
    elif os.path.exists(output_dir):
        raise FileExistsError(
            "Model directory already exists. Please remove it or use --force option."
        )

    default_configs_dir = find_dir("default_configs")
    shutil.copytree(default_configs_dir,
                    output_dir,
                    ignore=shutil.ignore_patterns("*.tmpl"))

    # extract script name and model class
    if not args.script:
        logger.warning(
            'You don\'t specify script path: by default, "./model.py" is used')
        script_path = "model.py"
    else:
        script_path = args.script

    if ":" not in script_path:
        model_classes = get_all_classes_inherited_LabelStudioMLBase(
            script_path)
        if len(model_classes) > 1:
            raise ValueError(
                "You don't specify target model class, and we've found {num} possible candidates within {script}. "
                "Please specify explicitly which one should be used using the following format:\n "
                "{script}:{model_class}".format(
                    num=len(model_classes),
                    script=script_path,
                    model_class=model_classes[0],
                ))
        model_class = model_classes[0]
    else:
        script_path, model_class = args.script.split(":")

    if not os.path.exists(script_path):
        raise FileNotFoundError(script_path)

    def use(filename):
        filepath = os.path.join(os.path.dirname(script_path), filename)
        if os.path.exists(filepath):
            shutil.copy2(filepath, output_dir)

    script_base_name = os.path.basename(script_path)
    use(script_base_name)
    use("requirements.txt")
    use("README.md")

    wsgi_script_file = os.path.join(default_configs_dir, "_wsgi.py.tmpl")
    with open(wsgi_script_file) as f:
        wsgi_script = f.read()
    wsgi_script = wsgi_script.format(
        script=os.path.splitext(script_base_name)[0], model_class=model_class)
    wsgi_name = os.path.basename(wsgi_script_file).split(".tmpl", 1)[0]
    with open(os.path.join(output_dir, wsgi_name), mode="w") as fout:
        fout.write(wsgi_script)

    print(Fore.GREEN +
          "Congratulations! ML Backend has been successfully initialized in " +
          output_dir)
    print(Fore.RESET + "Now start it by using:\n" + Fore.CYAN +
          "label-studio-ml start " + output_dir)
Exemplo n.º 14
0
LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True



# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'

from label_studio.utils.io import find_dir
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
    os.path.join(BASE_DIR, "flaskapp/static"),
    os.path.join(BASE_DIR, "mainapp/static"),
    find_dir('static'),
]

LOGIN_REDIRECT_URL = '/projects/list'
LOGOUT_REDIRECT_URL = '/login'
LOGIN_URL = '/login'

AUTH_USER_MODEL = 'mainapp.User'
Exemplo n.º 15
0
def parse_input_args():
    """Combine args with json config

    :return: config dict
    """
    import sys
    import argparse
    from label_studio.project import Project

    if len(sys.argv) == 1:
        print("\nQuick start usage: label-studio start my_project --init\n")

    available_templates = [
        os.path.basename(os.path.dirname(f)) for f in iter_config_templates()
    ]

    def valid_filepath(filepath):
        path = os.path.abspath(os.path.expanduser(filepath))
        if os.path.exists(path):
            return path
        raise FileNotFoundError(filepath)

    root_parser = argparse.ArgumentParser(add_help=False)
    root_parser.add_argument(
        "--version",
        dest="version",
        action="store_true",
        help="Show Label Studio version",
    )
    root_parser.add_argument(
        "-b",
        "--no-browser",
        dest="no_browser",
        action="store_true",
        help="Do not open browser at label studio start",
    )
    root_parser.add_argument(
        "-d",
        "--debug",
        dest="debug",
        action="store_true",
        help="Debug mode for Flask",
        default=None,
    )
    root_parser.add_argument(
        "--force",
        dest="force",
        action="store_true",
        help="Force overwrite existing files",
    )
    root_parser.add_argument("--root-dir",
                             dest="root_dir",
                             default=".",
                             help="Project root directory")
    root_parser.add_argument(
        "-v",
        "--verbose",
        dest="verbose",
        action="store_true",
        help="Increase output verbosity",
    )
    root_parser.add_argument(
        "--template",
        dest="template",
        choices=available_templates,
        help="Choose from predefined project templates",
    )
    root_parser.add_argument("-c",
                             "--config",
                             dest="config_path",
                             type=valid_filepath,
                             help="Server config")
    root_parser.add_argument(
        "-l",
        "--label-config",
        dest="label_config",
        type=valid_filepath,
        help="Label config path",
    )
    root_parser.add_argument(
        "-i",
        "--input-path",
        dest="input_path",
        type=valid_filepath,
        help="Input path for task file or directory with tasks",
    )
    root_parser.add_argument(
        "-s",
        "--source",
        dest="source",
        choices=Project.get_available_source_storages(),
        help="Source data storage type",
    )
    root_parser.add_argument("--source-path",
                             dest="source_path",
                             help="Source bucket name")
    root_parser.add_argument(
        "--source-params",
        dest="source_params",
        type=json.loads,
        default={},
        help="JSON string representing source parameters",
    )
    root_parser.add_argument(
        "-t",
        "--target",
        dest="target",
        choices=Project.get_available_target_storages(),
        help="Target data storage type",
    )
    root_parser.add_argument("--target-path",
                             dest="target_path",
                             help="Target bucket name")
    root_parser.add_argument(
        "--target-params",
        dest="target_params",
        type=json.loads,
        default={},
        help="JSON string representing target parameters",
    )
    root_parser.add_argument(
        "--input-format",
        dest="input_format",
        choices=("json", "json-dir", "text", "text-dir", "image-dir",
                 "audio-dir"),
        default="json",
        help=
        'Input tasks format. Unless you are using "json" or "json-dir" format, --label-config option is required',
    )
    root_parser.add_argument(
        "-o",
        "--output-dir",
        dest="output_dir",
        type=valid_filepath,
        help="Output directory for completions (unless cloud storage is used)",
    )
    root_parser.add_argument(
        "--ml-backends",
        dest="ml_backends",
        nargs="+",
        help="Machine learning backends URLs",
    )
    root_parser.add_argument(
        "--sampling",
        dest="sampling",
        choices=["sequential", "uniform"],
        default="sequential",
        help="Sampling type that defines tasks order",
    )
    root_parser.add_argument(
        "--log-level",
        dest="log_level",
        choices=["DEBUG", "INFO", "WARNING", "ERROR"],
        default=None,
        help="Logging level",
    )
    root_parser.add_argument(
        "--host",
        dest="host",
        type=str,
        help=
        "Server hostname for LS internal usage like import task urls generation, sample task urls, etc. "
        'If you need to start server on localhost instead of 0.0.0.0, just make it "localhost". '
        "Otherwise web-server host will be 0.0.0.0 always independent of this parameter.",
    )
    root_parser.add_argument("--protocol",
                             dest="protocol",
                             type=str,
                             help="Web protocol http:// or https://")
    root_parser.add_argument("-p",
                             "--port",
                             dest="port",
                             type=int,
                             help="Server port")
    root_parser.add_argument(
        "--cert",
        dest="cert_file",
        type=valid_filepath,
        help="Certificate file for HTTPS (in PEM format)",
    )
    root_parser.add_argument(
        "--key",
        dest="key_file",
        type=valid_filepath,
        help="Private key file for HTTPS (in PEM format)",
    )
    root_parser.add_argument(
        "--allow-serving-local-files",
        dest="allow_serving_local_files",
        action="store_true",
        help=
        "Allow serving local files (Warning! use this option only for your local runs)",
    )
    root_parser.add_argument(
        "--use-gevent",
        dest="use_gevent",
        action="store_true",
        help="Use gevent for better concurrency",
        default=False,
    )
    root_parser.add_argument(
        "--initial-project-description",
        dest="project_desc",
        help="Project description to identify project",
    )

    parser = argparse.ArgumentParser(description="Label studio")

    subparsers = parser.add_subparsers(dest="command",
                                       help="Available commands")
    subparsers.required = True

    # init sub-command parser

    parser_version = subparsers.add_parser("version",
                                           help="Print version info",
                                           parents=[root_parser])

    parser_init = subparsers.add_parser("init",
                                        help="Initialize Label Studio",
                                        parents=[root_parser])
    parser_init.add_argument(
        "project_name",
        help="Path to directory where project state will be initialized")

    # start sub-command parser

    parser_start = subparsers.add_parser("start",
                                         help="Start Label Studio server",
                                         parents=[root_parser])
    parser_start.add_argument(
        "project_name",
        help="Path to directory where project state has been initialized",
    )
    parser_start.add_argument(
        "--init",
        dest="init",
        action="store_true",
        help="Initialize if project is not initialized yet",
    )
    parser_start.add_argument("--password",
                              dest="password",
                              default="",
                              help="Password for web access")
    parser_start.add_argument("--username",
                              dest="username",
                              default="",
                              help="Username for web access")

    # start-multi-session sub-command parser

    parser_start_ms = subparsers.add_parser("start-multi-session",
                                            help="Start Label Studio server",
                                            parents=[root_parser])

    args = parser.parse_args()

    # print version
    if args.version or args.command == "version":
        from label_studio import __version__

        print("\nLabel Studio version:", __version__, "\n")

    if args.output_dir is not None:
        raise RuntimeError(
            '"--output-dir" option is deprecated and has no effect.\n'
            "All output results are saved to project_name/completions directory"
        )

    label_config_explicitly_specified = (hasattr(args, "label_config")
                                         and args.label_config)
    if args.template and not label_config_explicitly_specified:
        args.label_config = os.path.join(find_dir("examples"), args.template,
                                         "config.xml")
    if not hasattr(args, "label_config"):
        args.label_config = None
    return args