import csv


def read_tsv_file(file):
    """Read the TSV output file created by Tesseract

    Return a tuple (text, confidence)
    """
    # The tsv file has various columns, we are interested to the column 'conf'
    # and the column 'text'. The cells of 'text' column are concatenated and
    # with the confidence rates the average is calculated
    text_lines = []
    conf = 0
    words_count = 0
    with open(file) as output_file:
        reader = csv.DictReader(output_file, delimiter="\t", quotechar="|")
        text_line = []
        for row in reader:
            word_conf = float(row["conf"])
            if word_conf >= 0:
                text_line.append(row["text"])
                conf += word_conf
                words_count += 1
            else:
                text_lines.append(" ".join(c for c in text_line))
                text_line = []
        text_lines.append(" ".join(c for c in text_line))
    text = "\n".join(line for line in text_lines).strip()
    if words_count > 0:
        conf = conf / words_count
    return text, conf