File size: 1,150 Bytes
125db61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Normalise generated hypotheses before evaluation.

* converts LaTeX inline delimiters ``\\( ... \\)`` to ``$ ... $`` so that the
  Markdown and DOCX renderers agree;
* collapses excessive blank lines and trailing spaces;
* keeps the original text in ``text_raw`` on first run for auditability.
"""
from __future__ import annotations

import json
import re
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
HYPO = ROOT / "outputs" / "hypotheses"


def clean(text: str) -> str:
    text = text.replace("\\(", "$").replace("\\)", "$")
    text = text.replace("\\[", "$$").replace("\\]", "$$")
    text = re.sub(r"\n{3,}", "\n\n", text)
    text = re.sub(r"[ \t]+\n", "\n", text)
    return text.strip()


def main() -> None:
    n = 0
    for path in sorted(HYPO.glob("*.json")):
        rec = json.loads(path.read_text(encoding="utf-8"))
        rec.setdefault("text_raw", rec["text"])
        rec["text"] = clean(rec["text"])
        path.write_text(json.dumps(rec, ensure_ascii=False, indent=1), encoding="utf-8")
        n += 1
    print(f"normalised {n} records")


if __name__ == "__main__":
    main()