nv-kgmad / scripts /postprocess.py
eduzrh's picture
Upload NV-KGMAD code, data, cached responses, results and paper (part 8)
125db61 verified
Raw History Blame Contribute Delete
1.15 kB
#!/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()