gec-test-set / get_corrected_igc.py
thorunn's picture
Upload 3 files
afd42da
raw
history blame contribute delete
No virus
1.98 kB
import sys
import os
from xml.etree import ElementTree as ET
import json
from test_set_map import igc_map
def get_xml_paragraphs() -> ET.Element:
"""Return paragraphs from an original IGC XML file, defined by the imported igc_map."""
igc_file = igc_map[TEST_DATA_FILE]
igc_xml = os.path.join(IGC_PATH, igc_file + ".xml")
with open(igc_xml, "r") as f:
tree = ET.parse(f)
root = tree.getroot()
paragraphs = root[1][0][0]
return paragraphs
def get_correction_map() -> dict:
"""Get the correction map from a json file."""
with open(os.path.join(os.getcwd(), "Type2", "IGC", TEST_DATA_FILE + "_correction_map.json"), "r") as f:
correction_map = json.load(f)
correction_map = {int(k): v for k, v in correction_map.items()}
return correction_map
def change_text(correction_map, paragraphs) -> str:
"""Make corrections to the original text based on the correction map."""
corrected_text = []
for key, value in correction_map.items():
original_text = paragraphs[key].text
# Counter for the shift in index positions due to deletions
total_shift = 0
for idx, corr in value.items():
idx = int(idx)
# Account for any previous deletions in the text
adjusted_idx = idx + total_shift
if corr[0] == "del":
original_text = original_text[:adjusted_idx] + original_text[adjusted_idx + 1 :]
total_shift -= 1
elif corr[0] == "add":
original_text = original_text[:adjusted_idx] + corr[1] + original_text[adjusted_idx:]
corrected_text.append(original_text)
return "\n\n".join(corrected_text)
if __name__ == "__main__":
TEST_DATA_FILE = sys.argv[1]
IGC_PATH = sys.argv[2]
correction_map = get_correction_map()
xml_paragraphs = get_xml_paragraphs()
corrected_text = change_text(correction_map, xml_paragraphs)
print(corrected_text)