ocwcourses / ocwcourses.py
zhangir-azerbayev
rename
89638df
"""OCWCourses"""
import json
import os
import re
import zipfile
import datasets
logger = datasets.logging.get_logger(__name__)
_CITATION = """\
@misc{lewkowycz2022solving,
title={Solving Quantitative Reasoning Problems with Language Models},
author={Aitor Lewkowycz and Anders Andreassen and David Dohan and Ethan Dyer and Henryk Michalewski and Vinay Ramasesh and Ambrose Slone and Cem Anil and Imanol Schlag and Theo Gutman-Solo and Yuhuai Wu and Behnam Neyshabur and Guy Gur-Ari and Vedant Misra},
year={2022},
eprint={2206.14858},
archivePrefix={arXiv},
primaryClass={cs.CL}
}
"""
_DESCRIPTION = """\
OCWCourses
"""
_URL = "https://openreview.net/forum?id=IFXTZERXdM7"
_URLS = {
"test": "https://openreview.net/attachment?id=IFXTZERXdM7&name=supplementary_material",
}
def _read_from_zip(zip_path, text_filename='minerva_supplement/ocw_courses_problems.text'):
with zipfile.ZipFile(zip_path, 'r') as myzip:
with myzip.open(text_filename) as myfile:
return myfile.read().decode('utf-8')
def _parse_latex(text):
problems = re.findall(r'\\textbf{Problem:}(.*?)\\textbf{Solution:}', text, re.DOTALL)
solutions = re.findall(r'\\textbf{Solution:}(.*?)(\\textbf{Problem:}|$)', text, re.DOTALL)
parsed_list = []
for problem, solution in zip(problems, solutions):
parsed_list.append({
'problem': problem.strip(),
'solution': solution[0].strip()
})
return parsed_list
def _last_boxed_only_string(string):
idx = string.rfind("\\boxed")
if "\\boxed " in string:
return "\\boxed " + string.split("\\boxed ")[-1].split("$")[0]
if idx < 0:
idx = string.rfind("\\fbox")
if idx < 0:
return None
i = idx
right_brace_idx = None
num_left_braces_open = 0
while i < len(string):
if string[i] == "{":
num_left_braces_open += 1
if string[i] == "}":
num_left_braces_open -= 1
if num_left_braces_open == 0:
right_brace_idx = i
break
i += 1
if right_brace_idx is None:
retval = None
else:
retval = string[idx : right_brace_idx + 1]
return retval
def _remove_boxed(s):
if "\\boxed " in s:
left = "\\boxed "
assert s[: len(left)] == left
return s[len(left) :]
left = "\\boxed{"
assert s[: len(left)] == left
assert s[-1] == "}"
return s[len(left) : -1]
class OCWConfig(datasets.BuilderConfig):
"""BuilderConfig for OCW."""
def __init__(self, **kwargs):
"""BuilderConfig for OCW.
Args:
**kwargs: keyword arguments forwarded to super.
"""
super(OCWConfig, self).__init__(**kwargs)
class OCWCourses(datasets.GeneratorBasedBuilder):
"""OCWCourses"""
BUILDER_CONFIGS = [
OCWConfig(
name="ocwcourses",
version=datasets.Version("1.0.0", ""),
description="OCWCourses",
),
]
def _info(self):
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=datasets.Features(
{
"problem": datasets.Value("string"),
"solution": datasets.Value("string"),
"answer": datasets.Value("string"),
}
),
# No default supervised_keys (as we have to pass both question
# and context as input).
supervised_keys=None,
homepage="https://openreview.net/forum?id=IFXTZERXdM7",
citation=_CITATION,
)
def _split_generators(self, dl_manager):
downloaded_files = dl_manager.download_and_extract(_URLS)
return [
datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={"filepath": downloaded_files["test"]}),
]
def _generate_examples(self, filepath):
"""This function returns the examples in the raw (text) form."""
logger.info("generating examples from = %s", filepath)
with open(os.path.join(filepath, "minerva_supplement/ocw_courses_problems.tex")) as f:
text = f.read()
parsed_problems_solutions = _parse_latex(text)
rows = [{**x, "answer": _remove_boxed(_last_boxed_only_string(x["solution"]))} for x in parsed_problems_solutions]
for key, row in enumerate(rows):
yield key, row