Download evaluation/florian_evaluate.py from RfKnowledge/wp3-finepdfs-ocr-evaluation: direct link, hf CLI and curl.
- Browser
- Download file 4.99 kB
-
https://huggingface.co/datasets/RfKnowledge/wp3-finepdfs-ocr-evaluation/resolve/main/evaluation/florian_evaluate.py
- Command line
-
hf download hf://datasets/RfKnowledge/wp3-finepdfs-ocr-evaluation/evaluation/florian_evaluate.py
-
curl -L -o florian_evaluate.py https://huggingface.co/datasets/RfKnowledge/wp3-finepdfs-ocr-evaluation/resolve/main/evaluation/florian_evaluate.py
4.99 kB
| """ | |
| 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() | |