vanilla_biometrics.py 7.59 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Tiago de Freitas Pereira <tiago.pereira@idiap.ch>


"""Executes biometric pipeline"""

import os
import functools

import click

from bob.extension.scripts.click_helper import verbosity_option, ResourceOption, ConfigCommand

15
16
17
18
import logging
logger = logging.getLogger(__name__)


19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

EPILOG = """\b

 
 Command line examples\n
 -----------------------

 
 $ bob pipelines vanilla-biometrics my_experiment.py -vv


 my_experiment.py must contain the following elements:

 >>> preprocessor = my_preprocessor() \n
 >>> extractor = my_extractor() \n
 >>> algorithm = my_algorithm() \n
 >>> checkpoints = EXPLAIN CHECKPOINTING \n
 
\b


Look at the following example

 $ bob pipelines vanilla-biometrics ./bob/pipelines/config/distributed/sge_iobig_16cores.py \
                                    ./bob/pipelines/config/database/mobio_male.py \
                                    ./bob/pipelines/config/baselines/facecrop_pca.py

\b



TODO: Work out this help

"""


@click.command(
    entry_point_group='bob.pipelines.config', cls=ConfigCommand,
    epilog=EPILOG,
)
@click.option(
    "--preprocessor",
    "-p",
    required=True,
    cls=ResourceOption,
64
    entry_point_group="bob.bio.preprocessor",  # This should be linked to bob.bio.base
65
66
67
68
69
70
71
    help="Data preprocessing algorithm",
)
@click.option(
    "--extractor",
    "-e",
    required=True,
    cls=ResourceOption,
72
    entry_point_group="bob.bio.extractor",  # This should be linked to bob.bio.base
73
74
75
76
77
78
79
    help="Feature extraction algorithm",
)
@click.option(
    "--algorithm",
    "-a",
    required=True,
    cls=ResourceOption,
80
    entry_point_group="bob.bio.algorithm",  # This should be linked to bob.bio.base
81
82
83
84
85
86
87
    help="Biometric Algorithm (class that implements the methods: `fit`, `enroll` and `score`)",
)
@click.option(
    "--database",
    "-d",
    required=True,
    cls=ResourceOption,
88
    entry_point_group="bob.bio.database",  # This should be linked to bob.bio.base
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
    help="Biometric Database connector (class that implements the methods: `background_model_samples`, `references` and `probes`)",
)
@click.option(
    "--dask-client",
    "-l",
    required=True,
    cls=ResourceOption,
    entry_point_group="bob.pipelines.client",  # This should be linked to bob.bio.base
    help="Dask client for the execution of the pipeline.",
)
@click.option(
    "--checkpointing", "-c", is_flag=True, help="Save checkpoints in this experiment?"
)
@click.option(
    "--group",
    "-g",
    type=click.Choice(["dev", "eval"]),
    multiple=True,
    default=("dev",),
    help="If given, this value will limit the experiments belonging to a particular protocolar group",
)
@click.option(
    "-o",
    "--output",
    show_default=True,
    default="results",
    help="Name of output directory",
)
def vanilla_biometrics(
    preprocessor,
    extractor,
    algorithm,
    database,
    dask_client,
    checkpointing,
    group,
    output,
    **kwargs
):
    """Runs the simplest biometrics pipeline.

    Such pipeline consists into three sub-pipelines.
    In all of them, given raw data as input it does the following steps:

    Sub-pipeline 1:\n
    ---------------
    
    Training background model. Some biometric algorithms demands the training of background model, for instance, PCA/LDA matrix or a Neural networks. This sub-pipeline handles that and it consists of 3 steps:

    \b
    raw_data --> preprocessing >> feature extraction >> train background model --> background_model



    \b

    Sub-pipeline 2:\n
    ---------------
 
    Creation of biometric references: This is a standard step in a biometric pipelines.
    Given a set of samples of one identity, create a biometric reference (a.k.a template) for sub identity. This sub-pipeline handles that in 3 steps and they are the following:

    \b
    raw_data --> preprocessing >> feature extraction >> enroll(background_model) --> biometric_reference
    
    Note that this sub-pipeline depends on the previous one



    Sub-pipeline 3:\n
    ---------------


    Probing: This is another standard step in biometric pipelines. Given one sample and one biometric reference, computes a score. Such score has different meanings depending on the scoring method your biometric algorithm uses. It's out of scope to explain in a help message to explain what scoring is for different biometric algorithms.

 
    raw_data --> preprocessing >> feature extraction >> probe(biometric_reference, background_model) --> score

    Note that this sub-pipeline depends on the two previous ones


    """
171
    
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
    # Always turn-on the checkpointing
    checkpointing = True

    # Chooses the pipeline to run
    from bob.bio.base.pipelines.vanilla_biometrics import biometric_pipeline

    if not os.path.exists(output):
        os.makedirs(output)
 
    if checkpointing:
        checkpoints = {
            "background": {
                "preprocessor": os.path.join(output, "background", "preprocessed"),
                "extractor": os.path.join(output, "background", "extracted"),
                # at least, the next stage must be provided!
                "model": os.path.join(output, "background", "model"),
            },
            "references": {
                "preprocessor": os.path.join(output, "references", "preprocessed"),
                "extractor": os.path.join(output, "references", "extracted"),
                "enrolled": os.path.join(output, "references", "enrolled"),
            },
            "probes": {
                "preprocessor": os.path.join(output, "probes", "preprocessed"),
                "extractor": os.path.join(output, "probes", "extracted"),
            },
        }


    # Defines the processing pipeline for loading samples
    # Can add any number of steps!
    pipeline = [("preprocessor",preprocessor),
                ("extractor", extractor)]

    # Mechanism that loads samples
    # from ..bob_bio.blocks import SampleLoader
    from bob.bio.base.pipelines.annotated_blocks import SampleLoaderAnnotated as SampleLoader
    loader = SampleLoader(pipeline)

    for g in group:

        result = biometric_pipeline(
            database.background_model_samples(),
            database.references(group=g),
            database.probes(group=g),
            loader,
            algorithm,
            npartitions=len(dask_client.cluster.workers),
            checkpoints=checkpoints,
        )

        # result.visualize(os.path.join(output, "graph.pdf"), rankdir="LR")
        result = result.compute(scheduler=dask_client)
225
226
227
228
229
        with open(os.path.join(output,f"scores-{g}"), "w") as f:
            for probe in result:
                for reference in probe.samples:
                    line = "{0} {1} {2} {3}\n".format(reference.subject, probe.subject, probe.path, reference.data)
                    f.write(line)
230
231

    dask_client.shutdown()
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270



@click.command()
@click.argument("output-file")
@verbosity_option(cls=ResourceOption)
def vanilla_biometrics_template(output_file, **kwargs):
    """
    Generate an template configuration file for the vanilla biometrics pipeline
    """

    import bob.io.base

    path = os.path.dirname(output_file)
    logger.info(f"Writting template configuration file in {path}")
    bob.io.base.create_directories_safe(path)

    template = '''

# Client dask. Look at https://gitlab.idiap.ch/bob/bob.pipelines/tree/master/bob/pipelines/config/distributed to find proper dask clients.
# You don't need to necessary instantiate a dask client yourself. You can simply pipe those config files

dask_client = my_client


preprocessor = my_preprocessor


extractor = my_extractor


algorithm = my_algorithm


database = my_database
    
'''

    open(output_file, "w").write(template)