|
| 1 | +# Copyright (c) OpenMMLab. All rights reserved. |
| 2 | +import re |
| 3 | +from difflib import SequenceMatcher |
| 4 | +from typing import Dict, Sequence, Tuple |
| 5 | + |
| 6 | +from mmeval.core import BaseMetric |
| 7 | + |
| 8 | + |
| 9 | +class CharRecallPrecision(BaseMetric): |
| 10 | + r"""Calculate the char level recall & precision. |
| 11 | +
|
| 12 | + Args: |
| 13 | + letter_case (str): There are three options to alter the letter cases |
| 14 | +
|
| 15 | + - unchanged: Do not change prediction texts and labels. |
| 16 | + - upper: Convert prediction texts and labels into uppercase |
| 17 | + characters. |
| 18 | + - lower: Convert prediction texts and labels into lowercase |
| 19 | + characters. |
| 20 | +
|
| 21 | + Usually, it only works for English characters. Defaults to |
| 22 | + 'unchanged'. |
| 23 | + invalid_symbol (str): A regular expression to filter out invalid or |
| 24 | + not cared characters. Defaults to '[^A-Za-z0-9\u4e00-\u9fa5]'. |
| 25 | + **kwargs: Keyword parameters passed to :class:`BaseMetric`. |
| 26 | +
|
| 27 | + Examples: |
| 28 | + >>> from mmeval import CharRecallPrecision |
| 29 | + >>> metric = CharRecallPrecision() |
| 30 | + >>> metric(['helL', 'HEL'], ['hello', 'HELLO']) |
| 31 | + {'char_recall': 0.6, 'char_precision': 0.8571428571428571} |
| 32 | + >>> metric = CharRecallPrecision(letter_case='upper') |
| 33 | + >>> metric(['helL', 'HEL'], ['hello', 'HELLO']) |
| 34 | + {'char_recall': 0.7, 'char_precision': 1.0} |
| 35 | + """ |
| 36 | + |
| 37 | + def __init__(self, |
| 38 | + letter_case: str = 'unchanged', |
| 39 | + invalid_symbol: str = '[^A-Za-z0-9\u4e00-\u9fa5]', |
| 40 | + **kwargs): |
| 41 | + super().__init__(**kwargs) |
| 42 | + assert letter_case in ['unchanged', 'upper', 'lower'] |
| 43 | + self.letter_case = letter_case |
| 44 | + self.invalid_symbol = re.compile(invalid_symbol) |
| 45 | + |
| 46 | + def add(self, predictions: Sequence[str], groundtruths: Sequence[str]) -> None: # type: ignore # yapf: disable # noqa: E501 |
| 47 | + """Process one batch of data and predictions. |
| 48 | +
|
| 49 | + Args: |
| 50 | + predictions (list[str]): The prediction texts. |
| 51 | + groundtruths (list[str]): The ground truth texts. |
| 52 | + """ |
| 53 | + for pred, label in zip(predictions, groundtruths): |
| 54 | + if self.letter_case in ['upper', 'lower']: |
| 55 | + pred = getattr(pred, self.letter_case)() |
| 56 | + label = getattr(label, self.letter_case)() |
| 57 | + valid_label = self.invalid_symbol.sub('', label) |
| 58 | + valid_pred = self.invalid_symbol.sub('', pred) |
| 59 | + # number to calculate char level recall & precision |
| 60 | + true_positive_char_num = self._cal_true_positive_char( |
| 61 | + valid_pred, valid_label) |
| 62 | + self._results.append( |
| 63 | + (len(valid_label), len(valid_pred), true_positive_char_num)) |
| 64 | + |
| 65 | + def compute_metric(self, results: Sequence[Tuple[int, int, int]]) -> Dict: |
| 66 | + """Compute the metrics from processed results. |
| 67 | +
|
| 68 | + Args: |
| 69 | + results (list[tuple]): The processed results of each batch. |
| 70 | +
|
| 71 | + Returns: |
| 72 | + Dict: The computed metrics. The keys are the names of the |
| 73 | + metrics, and the values are corresponding results. |
| 74 | + """ |
| 75 | + gt_sum, pred_sum, true_positive_sum = 0.0, 0.0, 0.0 |
| 76 | + for gt, pred, true_positive in results: |
| 77 | + gt_sum += gt |
| 78 | + pred_sum += pred |
| 79 | + true_positive_sum += true_positive |
| 80 | + char_recall = true_positive_sum / max(gt_sum, 1.0) |
| 81 | + char_precision = true_positive_sum / max(pred_sum, 1.0) |
| 82 | + metric_results = {} |
| 83 | + metric_results['recall'] = char_recall |
| 84 | + metric_results['precision'] = char_precision |
| 85 | + return metric_results |
| 86 | + |
| 87 | + def _cal_true_positive_char(self, pred: str, gt: str) -> int: |
| 88 | + """Calculate correct character number in prediction. |
| 89 | +
|
| 90 | + Args: |
| 91 | + pred (str): Prediction text. |
| 92 | + gt (str): Ground truth text. |
| 93 | +
|
| 94 | + Returns: |
| 95 | + true_positive_char_num (int): The true positive number. |
| 96 | + """ |
| 97 | + |
| 98 | + all_opt = SequenceMatcher(None, pred, gt) |
| 99 | + true_positive_char_num = 0 |
| 100 | + for opt, _, _, s2, e2 in all_opt.get_opcodes(): |
| 101 | + if opt == 'equal': |
| 102 | + true_positive_char_num += (e2 - s2) |
| 103 | + else: |
| 104 | + pass |
| 105 | + return true_positive_char_num |
0 commit comments