import re


def parse_metrics(log_file, metric_names):
    """
    Parse the metric values from the log file.
    Note that we use the last matched value in the log file.
    For example, when metric is 'best_acc1', we will match
    the last line that look like
        - best_acc1 = 78.5
        - best_acc1: 43
        - best_acc1 100.

    :param log_file: (str) the name of the log file
    :param metric_names: (list(str)) the querying metric names
    :return:
    """
    values = []
    for metric_name in metric_names:
        metric_pattern = re.compile(metric_name + '[ =:]*([-+]?[0-9]*\.?[0-9]+)')
        value = ""
        with open(log_file, "r") as f:

            for line in reversed(f.readlines()):
                result = metric_pattern.search(line)
                if result:  # find the latest value
                    value = result.group(1)
                    break
        values.append(value)
    return values