File size: 4,992 Bytes
dc247f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
"""
Computes METRICS for finepdf samples (/scratch/project_465002891/oellm_pdf_audio_extraction/finepdfs_samples) predictions.
Predictions in each data.json must end with \"_prediction\". Adds metrics for each prediction in the data.json in the format {TOOL_METRIC}
and writes weighted scores for each language in a metrics.yaml file.
"""
import unicodedata
from collections import Counter
from pathlib import Path

import jiwer
import polars as pl
import yaml

METRICS = ("wer", "cer", "bow")


def normalize(text: str) -> str:
    """Unicode-normalize OCR text before comparison to avoid penalizing different bytes for same diacritics"""
    text = unicodedata.normalize("NFC", text)
    text = text.casefold()  # str.casefold() is Unicode-aware and safer than .lower()
    return text


def wer(gold: str, pred: str) -> float:
    return jiwer.wer(gold, pred)


def cer(gold: str, pred: str) -> float:
    return jiwer.cer(gold, pred)


def bag_of_words_f1(gold: str, pred: str) -> float:
    gold_words = Counter(gold.split())
    pred_words = Counter(pred.split())
    overlap = sum((gold_words & pred_words).values())
    precision = overlap / max(sum(pred_words.values()), 1)
    recall = overlap / max(sum(gold_words.values()), 1)
    f1 = 2 * precision * recall / (precision + recall) if (precision + recall) else 0.0
    return f1


def evaluate_folder(data_file: Path) -> tuple[pl.DataFrame, list[str]]:
    """Compute evaluation metrics on all columns ending with \"prediction\""""

    def normalize_and_compute_metrics(gold: str, pred: str) -> dict[str, float]:
        ngold, npred = normalize(gold), normalize(pred)
        return {
            "wer": wer(ngold, npred),
            "cer": cer(ngold, npred),
            "bow": bag_of_words_f1(ngold, npred),
        }

    df = pl.read_ndjson(data_file)

    gold_col = "text"
    pred_suffix = "_prediction"

    metrics_cols: list[str] = []
    metrics_exprs: list[pl.Expr] = []
    tool_names: list[str] = []
    tool_metrics_field_names: list[str] = []
    pred_cols = [col for col in df.columns if col.endswith(pred_suffix)]

    for pred_col in pred_cols:
        tool_name = pred_col[: -len(pred_suffix)]
        tool_names.append(tool_name)
        tool_metrics_field_names.extend(f"{tool_name}_{metric}" for metric in METRICS)
        gold_pred = pl.struct([gold_col, pred_col])
        metrics_col = f"{tool_name}_metrics"
        metrics_cols.append(metrics_col)

        metrics_exprs.append(
            gold_pred.map_elements(
                lambda row, gold=gold_col, pred=pred_col, tool=tool_name: {
                    f"{tool}_{k}": v
                    for k, v in normalize_and_compute_metrics(
                        row[gold], row[pred]
                    ).items()
                },
                return_dtype=pl.Struct(
                    {
                        f"{tool_name}_wer": pl.Float64,
                        f"{tool_name}_cer": pl.Float64,
                        f"{tool_name}_bow": pl.Float64,
                    }
                ),
            ).alias(metrics_col)
        )

    df = df.drop(
        [c for c in tool_metrics_field_names if c in df.columns]
    )  # remove previous metrics before computing new ones (unnest can't overwrite)
    return df.with_columns(metrics_exprs).unnest(metrics_cols), tool_names


def write_metrics_yaml(
    df: pl.DataFrame,
    tool_names: list[str],
    output_path: Path,
    gold_col: str = "text",
) -> None:
    """Writes weighted average for all metrics in a yaml file"""
    df = df.with_columns(pl.col(gold_col).str.len_chars().alias("_gold_len"))
    total_len = df["_gold_len"].sum()

    summary: dict[str, dict[str, float]] = {}

    for tool in tool_names:
        tool_prefix = f"{tool}_"
        tool_cols = [
            c for c in df.columns if c.startswith(tool_prefix) and c.endswith(METRICS)
        ]

        weighted = df.select(
            [
                ((pl.col(c) * pl.col("_gold_len")).sum() / total_len).alias(c)
                for c in tool_cols
            ]
        )

        summary[tool] = {
            col[len(tool_prefix) :]: float(weighted[col][0]) for col in tool_cols
        }

    with open(output_path, "w") as f:
        yaml.safe_dump(summary, f, sort_keys=False, default_flow_style=False)


def main():
    samples_root = Path(
        "/scratch/project_465002891/oellm_pdf_audio_extraction/finepdfs_samples"
    )
    for language_folder in samples_root.glob("*"):
        if not language_folder.is_dir():
            continue

        data_file = language_folder / "data.json"
        if not data_file.exists():
            continue

        metrics_df, tool_names = evaluate_folder(data_file)
        metrics_yaml_path = data_file.parent.absolute() / "metrics.yaml"

        metrics_df.write_ndjson(data_file.absolute())
        write_metrics_yaml(
            metrics_df,
            tool_names,
            metrics_yaml_path,
        )


if __name__ == "__main__":
    main()