File size: 12,457 Bytes
40c6d5b
 
 
 
 
 
 
 
 
 
 
 
 
 
adaef8a
 
40c6d5b
e62fa22
 
adaef8a
 
4e6e22b
 
ac2ff4a
adaef8a
 
40c6d5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aee4926
40c6d5b
4e6e22b
 
 
 
 
 
 
 
 
 
 
 
e62fa22
4e6e22b
40c6d5b
 
 
 
 
 
 
 
 
 
d63b569
 
 
 
 
 
 
 
40c6d5b
 
adaef8a
40c6d5b
 
 
 
 
 
 
4e6e22b
 
 
 
 
 
 
 
5f71887
4e6e22b
 
 
 
 
 
 
e62fa22
4e6e22b
 
 
3f71575
4e6e22b
 
786af2b
5f71887
4e6e22b
5f71887
 
 
4e6e22b
5f71887
 
 
 
 
 
 
e62fa22
 
 
5f71887
 
 
 
 
 
 
e62fa22
9b1f529
5f71887
d63b569
4e6e22b
 
5f71887
 
 
 
 
 
415af94
4e6e22b
d63b569
adaef8a
4b2994b
 
adaef8a
 
 
 
76d1d0d
adaef8a
 
 
538cc7b
adaef8a
 
9955f8a
adaef8a
 
9955f8a
adaef8a
 
9955f8a
adaef8a
 
 
 
 
 
67a9a4f
c29fdef
67a9a4f
 
 
 
 
 
 
 
5417db0
538cc7b
 
 
67a9a4f
538cc7b
67a9a4f
adaef8a
c29fdef
 
 
 
adaef8a
 
 
0175937
d63b569
0175937
 
fa350f6
22a0855
0175937
d63b569
 
0175937
fa350f6
 
adaef8a
 
 
 
 
9955f8a
a90cb74
c4fe18d
363365d
 
 
 
 
 
 
 
 
 
 
 
 
22a0855
adaef8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
538cc7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adaef8a
 
 
48b7919
adaef8a
 
40c6d5b
adaef8a
4e6e22b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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
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
225
226
227
228
229
230
231
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import datetime
import os

from tqdm import tqdm

import datasets
import evaluate
from seametrics.user_friendly.utils import payload_to_uf_metrics, UFM
from seametrics.payload import Payload

import wandb

_CITATION = """\
@InProceedings{huggingface:module,
title = {A great new module},
authors={huggingface, Inc.},
year={2020}
}\
@article{milan2016mot16,
  title={MOT16: A benchmark for multi-object tracking},
  author={Milan, Anton and Leal-Taix{\'e}, Laura and Reid, Ian and Roth, Stefan and Schindler, Konrad},
  journal={arXiv preprint arXiv:1603.00831},
  year={2016}
}
"""

_DESCRIPTION = """\
The MOT Metrics module is designed to evaluate multi-object tracking (MOT) 
algorithms by computing various metrics based on predicted and ground truth bounding 
boxes. It serves as a crucial tool in assessing the performance of MOT systems, 
aiding in the iterative improvement of tracking algorithms."""


_KWARGS_DESCRIPTION = """

Calculates how good are predictions given some references, using certain scores
Args:
    predictions: list of predictions to score. Each predictions
        should be a string with tokens separated by spaces.
    references: list of reference for each prediction. Each
        reference should be a string with tokens separated by spaces.
    max_iou (`float`, *optional*):
        If specified, this is the minimum Intersection over Union (IoU) threshold to consider a detection as a true positive.
        Default is 0.5.
"""

@evaluate.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION)
class UserFriendlyMetrics(evaluate.Metric):
    """TODO: Short description of my evaluation module."""
    def __init__(
        self,
        iou_threshold: float = 1e-10,
        recognition_thresholds=[0.3, 0.5, 0.8],
        filter_dict={"name": "area", "ranges": [("all", [0, 1e5**2])]},
        **kwargs):
        super().__init__(**kwargs)

        # save parameters for later
        self.iou_threshold = iou_threshold
        self.filter_dict = filter_dict
        self.recognition_thresholds = recognition_thresholds
        self.metric = UFM(iou_threshold, recognition_thresholds)


    def _info(self):
        # TODO: Specifies the evaluate.EvaluationModuleInfo object
        return evaluate.MetricInfo(
            # This is the description that will appear on the modules page.
            module_type="metric",
            description=_DESCRIPTION,
            citation=_CITATION,
            inputs_description=_KWARGS_DESCRIPTION,
            # This defines the format of each prediction and reference
            features=datasets.Features({
                "predictions": datasets.Sequence(
                                datasets.Sequence(datasets.Value("float"))
                            ),
                "references": datasets.Features({ "all":
                                datasets.Sequence(datasets.Sequence(datasets.Value("float")))}
                            )
            }), #couldn't get this to work
            # Additional links to the codebase or references
            codebase_urls=["http://github.com/path/to/codebase/of/new_module"],
            reference_urls=["http://path.to.reference.url/new_module"],
        )

    def _download_and_prepare(self, dl_manager):
        """Optional: download external resources useful to compute the scores"""
        # TODO: Download external resources if needed
        pass

    def _compute(
        self, 
        predictions,
        references,
        ):

        results = {}
        filter_ranges = self.filter_dict["ranges"]
        
        for filter_range in filter_ranges:
            
            filter_range_name = filter_range[0]
            range_results = {}

            for sequence_predictions, sequence_references in zip(predictions, references):
                
                sequence_range_results = self.metric.calculate(
                    sequence_predictions,
                    sequence_references[filter_range_name],
                )

                range_results = sum_dicts(range_results, sequence_range_results)

            results[filter_range_name] = self.metric.derive_scores(range_results, self.recognition_thresholds)
        
        return results

    def compute_from_payload(self, 
        payload: Payload, 
        ):

        results = {}

        for model_name in payload.models:
            results[model_name] = {"overall": {}, "per_sequence": {}}
            
            # per-sequence loop
            progress_bar = tqdm(payload.sequences.items())
            for seq_name, sequence in progress_bar:
                progress_bar.set_description(f"Getting sequence payload: {seq_name}")
                # create new payload only with specific sequence and model
                sequence_payload = Payload(
                    dataset=payload.dataset,
                    gt_field_name=payload.gt_field_name,
                    models=[model_name],
                    sequences={seq_name: sequence}
                )
                progress_bar.set_description(f"Processing sequence: {seq_name}")
                predictions, references = payload_to_uf_metrics(sequence_payload, model_name=model_name, filter_dict=self.filter_dict)

                results[model_name]["per_sequence"][seq_name] = self._compute(predictions=predictions, references=references)

            # overall 
            model_payload = Payload(
                    dataset=payload.dataset,
                    gt_field_name=payload.gt_field_name,
                    models=[model_name],
                    sequences=payload.sequences
                )
            predictions, references = payload_to_uf_metrics(model_payload, model_name=model_name, filter_dict=self.filter_dict)

            results[model_name]["overall"] = self._compute(predictions=predictions, references=references)

        return results

    def wandb(
        self,
        results,
        wandb_section: str = None,
        wandb_runs = None,
        wandb_project="user_friendly_metrics",
        log_plots: bool = True,
        debug: bool = False,
        log_per_sequence = False
    ):
        """
        Logs metrics to Weights and Biases (wandb) for tracking and visualization, including categorized bar charts for overall metrics.

        Args:
            results (dict): Results dictionary with 'overall' and 'per_sequence' keys.
            wandb_section (str, optional): W&B section for metric grouping. Defaults to None.
            wandb_project (str, optional): The name of the wandb project. Defaults to 'user_friendly_metrics'.
            log_plots (bool, optional): Generates categorized bar charts for overall metrics. Defaults to True.
            debug (bool, optional): Logs detailed summaries and histories to the terminal console. Defaults to False.
        """

        current_datetime = datetime.datetime.now()
        formatted_datetime = current_datetime.strftime("%Y-%m-%d_%H-%M-%S")
        wandb.login(key=os.getenv("WANDB_API_KEY"))
        
        if wandb_runs is not None:
            assert len(wandb_runs) == len(results), "runs and results must have the same length"
        else:
            wandb_runs = [f"{i}_{formatted_datetime}" for i in list(results.keys())]

        for wandb_run_name, result in zip(wandb_runs, results.values()):        
            self.wandb_run(result = result, 
                    wandb_run_name = wandb_run_name, 
                    wandb_project = wandb_project, 
                    debug = debug,
                    wandb_section = wandb_section,
                    log_plots = log_plots,
                    log_per_sequence = log_per_sequence)

    def wandb_run(self, result, wandb_run_name, wandb_project, debug, wandb_section = None, log_plots = True, log_per_sequence = False):
            
        run = wandb.init(
            project = wandb_project,
            name = wandb_run_name,
            reinit = True,
            settings = wandb.Settings(silent=not debug),
        )

        categories = {
            "user_friendly_metrics": {
                f"mostly_tracked_score_{str(threshold).replace('.', '_')}" for threshold in self.recognition_thresholds
            },
            "evaluation_metrics_dev": {
                "recall",
            },
            "user_friendly_metrics_dev": {
                f"mostly_tracked_count_{str(threshold).replace('.', '_')}" for threshold in self.recognition_thresholds
            }.union("unique_object_count"),
            "predictions_summary": {
                "tp",
                "fn",
            },
        }

        chart_data = {key: [] for key in categories.keys()}

        # Log overall metrics
        if "overall" in result:
            for metric, value in result["overall"]["all"].items():
                log_key = (
                    f"{wandb_section}/overall/{metric}"
                    if wandb_section
                    else f"overall/{metric}"
                )
                run.log({log_key: value})

                if debug:
                    print(f" {log_key} = {value}")

                for category, metrics in categories.items():
                    if metric in metrics:
                        chart_data[category].append([metric, value])
            print("----------------------------------------------------")

        if log_plots:
            for category, data in chart_data.items():
                if data:
                    table_data = [[label, value] for label, value in data]
                    table = wandb.Table(data=table_data, columns=["metrics", "value"])
                    run.log(
                        {
                            f"{category}_bar_chart": wandb.plot.bar(
                                table,
                                "metrics",
                                "value",
                                title=f"{category.replace('_', ' ').title()}",
                            )
                        }
                    )

        if log_per_sequence:
            if "per_sequence" in result:
                sorted_sequences = sorted(
                    result["per_sequence"].items(),
                    key=lambda x: next(iter(x[1].values()), {}).get("all", {}).get("recall", 0),
                    reverse=True,  # Set to True for descending order
                )
    
                for sequence_name, sequence_data in sorted_sequences:
                    for metric, value in sequence_data["all"].items():
                        log_key = (
                            f"{wandb_section}/per_sequence/{sequence_name}/{metric}"
                            if wandb_section
                            else f"per_sequence/{sequence_name}/{metric}"
                        )
                        run.log({log_key: value})
                        if debug:
                            print(f" {log_key} = {value}")
                    print("----------------------------------------------------")

        if debug:
            print("\nDebug Mode: Logging Summary and History")
            print(f"Results Summary:\n{result}")
            print(f"WandB Settings:\n{run.settings}")
            print("All metrics have been logged.")

        run.finish()

def sum_dicts(*dicts):
    """
    Sums multiple dictionaries with depth one. If keys overlap, their values are summed.
    If keys are unique, they are simply included in the result.

    Args:
        *dicts: Any number of dictionaries to be summed.

    Returns:
        A single dictionary with the summed values.
    """
    result = {}
    for d in dicts:
        for key, value in d.items():
            if key in result:
                result[key] += value
            else:
                result[key] = value
    return result