6 from typing import Callable, List, NamedTuple, Optional, Set
11 logger = logging.getLogger(__name__)
12 parser = config.add_commandline_args(
13 f"ML Quick Labeler ({__file__})",
14 "Args related to quick labeling of ML training data",
17 "--ml_quick_label_skip_list_path",
18 default="./qlabel_skip_list.txt",
20 type=argparse_utils.valid_filename,
21 help="Path to file in which to store already labeled data.",
24 "--ml_quick_label_use_skip_lists",
26 action=argparse_utils.ActionNoYes,
27 help='Should we use a skip list file to speed up execution?',
30 "--ml_quick_label_overwrite_labels",
32 action=argparse_utils.ActionNoYes,
33 help='Enable overwriting existing labels; default is to not relabel.',
37 class InputSpec(NamedTuple):
38 image_file_glob: Optional[str]
39 image_file_prepopulated_list: Optional[List[str]]
40 image_file_to_features_file: Callable[[str], str]
42 valid_keystrokes: List[str]
44 keystroke_to_label: Callable[[str], str]
47 def read_skip_list() -> Set[str]:
49 if config.config['ml_quick_label_use_skip_lists']:
50 quick_skip_file = config.config['ml_quick_label_skip_list_path']
51 if os.path.exists(quick_skip_file):
52 with open(quick_skip_file, 'r') as f:
58 logger.debug(f'Read {quick_skip_file} and found {len(ret)} entries.')
62 def write_skip_list(skip_list) -> None:
63 if config.config['ml_quick_label_use_skip_lists']:
64 quick_skip_file = config.config['ml_quick_label_skip_list_path']
65 with open(quick_skip_file, 'w') as f:
66 for filename in skip_list:
67 filename = filename.strip()
69 f.write(f'{filename}\n')
70 logger.debug(f'Updated {quick_skip_file}')
73 def label(in_spec: InputSpec) -> None:
77 if in_spec.image_file_glob is not None:
78 images += glob.glob(in_spec.image_file_glob)
79 elif in_spec.image_file_prepopulated_list is not None:
80 images += in_spec.image_file_prepopulated_list
83 'One of image_file_glob or image_file_prepopulated_list is required'
86 skip_list = read_skip_list()
88 if image in skip_list:
89 logger.debug(f'Skipping {image} because of the skip list')
91 features = in_spec.image_file_to_features_file(image)
92 if features is None or not os.path.exists(features):
94 f'File {image} yielded file {features} which does not exist, SKIPPING.'
98 # Render features and image.
100 with open(features, "r") as f:
101 lines = f.readlines()
105 if in_spec.label not in line:
106 filtered_lines.append(line)
110 if not saw_label or config.config['ml_quick_label_overwrite_labels']:
111 logger.info(features)
112 os.system(f'xv {image} &')
113 keystroke = input_utils.single_keystroke_response(
114 in_spec.valid_keystrokes,
115 prompt=in_spec.prompt,
117 os.system('killall xv')
118 label_value = in_spec.keystroke_to_label(keystroke)
119 filtered_lines.append(f"{in_spec.label}: {label_value}\n")
120 with open(features, 'w') as f:
121 f.writelines("%s\n" % line for line in filtered_lines)
123 write_skip_list(skip_list)