import click


def pipe(required=True, mode='r'):
    """
    Allows you to use either a file stream or a standard stream as the value of the command argument.

    Arguments:
        required (bool): required argument (for write is not affected).
        mode (str): file open mode.

    Returns:
        (tuple): tuple containing:

            stream (io.IOBase): opened io stream.
            filename (str): filename, or None if using a standard stream.
    """
    def validate(ctx, param, value):
        if value is not None:
            return click.open_file(value, mode=mode, lazy=True), value

        get_stream = click.get_binary_stream if 'b' in mode else click.get_text_stream

        if 'r' not in mode:
            return get_stream('stdout'), None

        stream = get_stream('stdin')

        if not stream.isatty():
            return stream, None

        if required:
            raise click.MissingParameter(ctx=ctx, param=param)

        return None, None
    return validate