import re


def whitespace_trimmer(text, loader_context):
    """
    Removes all whitespace at either end of the string and replaces every
    substring with more than one internal space with a single space.
    Example: '  foo   bar baz   ' -> 'foo bar baz'
    """
    return re.sub(r'\s+', ' ', text.strip())