def detect_encoding(fp, default=None):
init_pos = fp.tell()<EOL>try:<EOL><INDENT>sample = fp.read(<EOL>current_app.config.get('<STR_LIT>', <NUM_LIT>))<EOL>result = cchardet.detect(sample)<EOL>threshold = current_app.config.get('<STR_LIT>', <NUM_LIT>)<EOL>if result.get('<STR_LIT>', <NUM_LIT:0>) > threshold:<EOL><INDENT>return result.get('<STR_LIT>', default)<EOL><DEDENT>else:<EOL><INDENT>return default<EOL><DEDENT><DEDENT>except Exception:<EOL><INDENT>current_app.logger.warning('<STR_LIT>', exc_info=True)<EOL>return default<EOL><DEDENT>finally:<EOL><INDENT>fp.seek(init_pos)<EOL><DEDENT>
Detect the cahracter encoding of a file.

    :param fp: Open Python file pointer.
    :param default: Fallback encoding to use.
    :returns: The detected encoding.

    .. note:: The file pointer is returned at its original read position.