remove_by_license.py 2.3 KB
import argparse
import os
import shutil


LICENCES2REMOVE = [
    'CC BY-NC-ND Creative Commons-Uznanie autorstwa - Użycie niekomercyjne - Bez utworów zależnych 3.0 PL',
    'CC BY-NC-ND Creative Commons-Uznanie autorstwa - Użycie niekomercyjne - Bez utworów zależnych 4.0',
    'CC BY-ND Creative Commons Uznanie autorstwa - Bez utworów zależnych 3.0 PL',
    'CC BY-ND Creative Commons Uznanie autorstwa - Bez utworów zależnych 4.0'
]


def main():
    args = parse_arguments()
    if not args.input or not args.output:
        print('Error: Input and output must be selected!')
    remove_by_license(args.input, args.output)


def parse_arguments():
    parser = argparse.ArgumentParser(description='Remove documents by selected licenses.')
    parser.add_argument('-o', '--output', help='output directory')
    required_arguments = parser.add_argument_group('required arguments')
    required_arguments.add_argument('-i', '--input', help='corpora root directory', required=True)
    return parser.parse_args()


def remove_by_license(root_directory, out_corpora_directory):
    for root, dirs, files in os.walk(root_directory):
        for filename in files:
            if filename.endswith('.conllup') or filename.endswith('.conllu'):
                src = os.path.join(root, filename)
                licence = get_licence(src)
                os.makedirs(out_corpora_directory, exist_ok=True)
                dst = os.path.join(out_corpora_directory, filename)
                if licence not in LICENCES2REMOVE:
                    shutil.copyfile(src, dst)


def get_licence(filepath):
    with open(filepath, 'r') as conllup_file:
        for line in conllup_file:
            line = line.strip()
            if is_segment(line):
                continue
            elif is_metadata(line):
                name, value = get_metadata(line)
                if name == 'Licence':
                    return value
    return '0'


def is_segment(line):
    if line and line[0].isdigit():
        return True
    return False


def is_metadata(line):
    if line.startswith('#'):
        return True
    return False


def get_metadata(line):
    name_value_pair = line.split('=', 1)
    name = name_value_pair[0].lstrip('#').strip()
    value = name_value_pair[1].strip()
    return name, value


if __name__ == '__main__':
    main()