import collections


def compute_f1_single(prediction, ground_truth):
  """Computes F1 score for a single prediction/ground_truth pair.

  This function computes the token-level intersection between the predicted and
  ground-truth answers, consistent with the SQuAD evaluation script.

  This is different from another common way of computing F1 (e.g. used by BiDAF)
  that uses the intersection between predicted answer span and ground-truth
  spans. The main difference is that this method gives credit to correct partial
  answers that don't match any full answer span, while the other one wouldn't.

  Args:
    prediction: predicted string.
    ground_truth: ground truth string.

  Returns:
    Token-wise F1 score between the two input strings.
  """
  # Handle empty answers for Squad 2.0.
  if not ground_truth and not prediction:
    return 1.0

  prediction_tokens = prediction.split()
  ground_truth_tokens = ground_truth.split()
  common = collections.Counter(prediction_tokens) & collections.Counter(
      ground_truth_tokens)
  num_same = sum(common.values())
  if num_same == 0:
    return 0.0
  precision = num_same / len(prediction_tokens)
  recall = num_same / len(ground_truth_tokens)
  f1 = (2 * precision * recall) / (precision + recall)
  return f1