Harbor format: 502 knowledge_work tasks (part 6)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+33
- tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/solution/solve.shAdded+4
- tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/task.tomlAdded+44
- tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/tests/expected.jsonAdded+60
- tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/tests/grade.pyAdded+330
- tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/tests/test.shAdded+4
- tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/validation/openenv.jsonAdded+26
- tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/environment/inputs/FTENETWORKS_INC_02_18_2016-EX-99.4-STRATEGIC_ALLIANCE_AGREEMENT.pdfAdded+3
- tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/instruction.mdAdded+23
- tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/solution/files/answer.jsonAdded+10
- tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/solution/solve.shAdded+4
- tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/task.tomlAdded+44
- tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/tests/expected.jsonAdded+60
- tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/tests/grade.pyAdded+330
- tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/tests/test.shAdded+4
- tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/validation/openenv.jsonAdded+26
- tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/environment/inputs/FulucaiProductionsLtd_20131223_10-Q_EX-10.9_8368347_EX-10.9_Content_License_Agreement.pdfAdded+3
- tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/instruction.mdAdded+22
- tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/solution/files/answer.jsonAdded+9
- tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/solution/solve.shAdded+4
- tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/task.tomlAdded+44
- tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/tests/expected.jsonAdded+59
- tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/tests/grade.pyAdded+330
- tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/tests/test.shAdded+4
- tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/validation/openenv.jsonAdded+26
- tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/environment/inputs/GlobalTechnologiesGroupInc_20050928_10KSB_EX-10.9_4148808_EX-10.9_Content_License_Agreement.pdfAdded+3
- tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/instruction.mdAdded+23
- tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/solution/files/answer.jsonAdded+10
- tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/solution/solve.shAdded+4
- tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/task.tomlAdded+44
- tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/tests/expected.jsonAdded+66
- tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/tests/grade.pyAdded+330
- tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/tests/test.shAdded+4
- tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/validation/openenv.jsonAdded+26
- tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/environment/inputs/GluMobileInc_20070319_S-1A_EX-10.09_436630_EX-10.09_Content_License_Agreement1.pdfAdded+3
- tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/instruction.mdAdded+23
- tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/solution/files/answer.jsonAdded+10
- tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/solution/solve.shAdded+4
- tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/task.tomlAdded+44
- tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/tests/expected.jsonAdded+66
- tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/tests/grade.pyAdded+330
- tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/tests/test.shAdded+4
- tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/validation/openenv.jsonAdded+26
- tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/environment/inputs/GOLDRESOURCECORP_12_11_2008-EX-10.1-STRATEGIC_ALLIANCE_AGREEMENT.pdfAdded+3
- tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/instruction.mdAdded+22
- tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/solution/files/answer.jsonAdded+9
- tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/solution/solve.shAdded+4
- tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/task.tomlAdded+44
- tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/tests/expected.jsonAdded+59
- tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/tests/grade.pyAdded+330
163 unmodified lines164165166163 unmodified linestasks/cuad-dd-elfbeauty-inc-07-02-2020-ex-10-1-coopera-4857c747/environment/inputs/ELFBEAUTY_INC_07_02_2020-EX-10.1-COOPERATION_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-euromediaholdingscorp-20070215-10sb12g-e-28af50c4/environment/inputs/EuromediaHoldingsCorp_20070215_10SB12G_EX-10.B_01__525118_EX-10.B_01__Content_License_Agreement.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/environment/inputs/FIBROGENINC_10_01_2014-EX-10.11-COLLABORATION_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -text163 unmodified lines164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199163 unmodified linestasks/cuad-dd-elfbeauty-inc-07-02-2020-ex-10-1-coopera-4857c747/environment/inputs/ELFBEAUTY_INC_07_02_2020-EX-10.1-COOPERATION_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-euromediaholdingscorp-20070215-10sb12g-e-28af50c4/environment/inputs/EuromediaHoldingsCorp_20070215_10SB12G_EX-10.B_01__525118_EX-10.B_01__Content_License_Agreement.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/environment/inputs/FIBROGENINC_10_01_2014-EX-10.11-COLLABORATION_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/environment/inputs/FTENETWORKS_INC_02_18_2016-EX-99.4-STRATEGIC_ALLIANCE_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/environment/inputs/FulucaiProductionsLtd_20131223_10-Q_EX-10.9_8368347_EX-10.9_Content_License_Agreement.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/environment/inputs/GlobalTechnologiesGroupInc_20050928_10KSB_EX-10.9_4148808_EX-10.9_Content_License_Agreement.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/environment/inputs/GluMobileInc_20070319_S-1A_EX-10.09_436630_EX-10.09_Content_License_Agreement1.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/environment/inputs/GOLDRESOURCECORP_12_11_2008-EX-10.1-STRATEGIC_ALLIANCE_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-gpaqacquisitionholdingsinc-20200123-s-4a-24fcbe48/environment/inputs/GpaqAcquisitionHoldingsInc_20200123_S-4A_EX-10.6_11951677_EX-10.6_License_Agreement.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-gridironbionutrients-inc-02-05-2020-ex-1-5a68fb60-v2/environment/inputs/GRIDIRONBIONUTRIENTS_INC_02_05_2020-EX-10.3-SUPPLY_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-healthgatedatacorp-11-24-1999-ex-10-1-ho-c456bfc3/environment/inputs/HEALTHGATEDATACORP_11_24_1999-EX-10.1-HOSTING_AND_MANAGEMENT_AGREEMENT_1.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-ibioinc-20200313-8-k-ex-10-1-12052678-ex-5ded7f3c-v2/environment/inputs/IbioInc_20200313_8-K_EX-10.1_12052678_EX-10.1_Development_Agreement.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-ideanomicsinc-20160330-10-k-ex-10-26-951-34feb55f/environment/inputs/IdeanomicsInc_20160330_10-K_EX-10.26_9512211_EX-10.26_Content_License_Agreement.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-idreamskytechnologyltd-07-03-2014-ex-10--92e3e5c0-v2/environment/inputs/IDREAMSKYTECHNOLOGYLTD_07_03_2014-EX-10.39-Cooperation_Agreement_on_Mobile_Game_Business.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-igenebiotechnologyinc-05-13-2003-ex-1-jo-71fbfebb-v2/environment/inputs/IGENEBIOTECHNOLOGYINC_05_13_2003-EX-1-JOINT_VENTURE_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-iminecorp-20180725-s-1-ex-10-5-11275970--06080324-v2/environment/inputs/ImineCorp_20180725_S-1_EX-10.5_11275970_EX-10.5_Distributor_Agreement.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-impressecorp-20000322-s-1a-ex-10-11-5199-95c2d66c/environment/inputs/ImpresseCorp_20000322_S-1A_EX-10.11_5199234_EX-10.11_Co-Branding_Agreement.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-internationalfastfoodcorp-04-04-1997-ex--4f3232be-v3/environment/inputs/INTERNATIONALFASTFOODCORP_04_04_1997-EX-99-FRANCHISE_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-intersectent-inc-05-11-2020-ex-10-1-supp-cb82a343-v2/environment/inputs/INTERSECTENT_INC_05_11_2020-EX-10.1-SUPPLY_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-iovancebiotherapeutics-inc-08-03-2017-ex-5067cd14/environment/inputs/IOVANCEBIOTHERAPEUTICS_INC_08_03_2017-EX-10.1-STRATEGIC_ALLIANCE_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-jingweiinternationalltd-10-04-2007-ex-10-6361913d/environment/inputs/JINGWEIINTERNATIONALLTD_10_04_2007-EX-10.7-INTELLECTUAL_PROPERTY_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-lejuholdingsltd-20140121-drs-on-f-1-ex--daa077cf/environment/inputs/LejuHoldingsLtd_20140121_DRS_on_F-1__EX-10.26_8473102_EX-10.26_Content_License_Agreement1.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-loyaltypointinc-11-16-2004-ex-10-2-resel-96103a19/environment/inputs/LOYALTYPOINTINC_11_16_2004-EX-10.2-RESELLER_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-magenta-therapeutics-inc---master-devel-4b001d95/environment/inputs/Magenta_Therapeutics_Inc._-_Master_Development_and_Manufacturing_Agreement.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-ofgbancorp-03-28-2007-ex-10-23-outsourci-6d2c44f4/environment/inputs/OFGBANCORP_03_28_2007-EX-10.23-OUTSOURCING_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-oldapiwind-downltd-01-08-2016-ex-1-3-age-36744ba9/environment/inputs/OLDAPIWIND-DOWNLTD_01_08_2016-EX-1.3-AGENCY_AGREEMENT1.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-paratekpharmaceuticalsinc-20170505-10-ka-9136ba4e/environment/inputs/ParatekPharmaceuticalsInc_20170505_10-KA_EX-10.29_10323872_EX-10.29_Outsourcing_Agreement.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-pelicandeliversinc-20200211-s-1-ex-10-3--5a88247f/environment/inputs/PelicanDeliversInc_20200211_S-1_EX-10.3_11975895_EX-10.3_Development_Agreement2.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-premierbiomedicalinc-05-14-2020-ex-10-2--a6870dfb/environment/inputs/PREMIERBIOMEDICALINC_05_14_2020-EX-10.2-INTELLECTUAL_PROPERTY_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-rareelementresourcesltd-20171019-sc-13d--1ce0b720/environment/inputs/RareElementResourcesLtd_20171019_SC_13D_EX-99.4_10897534_EX-99.4_Intellectual_Property_Agreement.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-reganholdingcorp-03-31-2008-ex-10-licens-68a0b439/environment/inputs/REGANHOLDINGCORP_03_31_2008-EX-10-LICENSE_AND_HOSTING_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-reynoldsconsumerproductsinc-20200121-s-1-7fd06763/environment/inputs/ReynoldsConsumerProductsInc_20200121_S-1A_EX-10.22_11948918_EX-10.22_Service_Agreement.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-rubiosrestaurantsinc-03-31-2008-ex-10-75-04fcb1ea-v2/environment/inputs/RUBIOSRESTAURANTSINC_03_31_2008-EX-10.75-SPONSORSHIP_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-scoutcaminc-05-12-2020-ex-10-22-services-2af3cb66/environment/inputs/SCOUTCAMINC_05_12_2020-EX-10.22-SERVICES_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-spienergyco-ltd-03-09-2011-ex-99-5-opera-c468dc5d/environment/inputs/SPIENERGYCO_LTD_03_09_2011-EX-99.5-OPERATIONS_AND_MAINTENANCE_AGREEMENT.pdf filter=lfs diff=lfs merge=lfs -texttasks/cuad-dd-stampscominc-20001114-10-q-ex-10-47-2631-979f273c-v2/environment/inputs/StampscomInc_20001114_10-Q_EX-10.47_2631630_EX-10.47_Co-Branding_Agreement.pdf filter=lfs diff=lfs merge=lfs -text
1234#!/bin/shset -eumkdir -p /workspace/outputscp -R /solution/files/. /workspace/outputs/1234567891011121314151617181920212223242526272829303132333435363738394041424344schema_version = "1.3"
[task]name = "apex-gap/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028"
[metadata.apex_gap]capability_tags = ["legal-documents", "pdf-extraction"]job = "corporate-law"source = "theatticusproject/cuad"source_license = "CC-BY-4.0"source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1"source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)"source_task_id = "FIBROGENINC_10_01_2014-EX-10.11-COLLABORATION AGREEMENT.PDF:agreement_date,exclusivity,most_favored_nation,audit_rights,ip_ownership_assignment,liquidated_damages,source_code_escrow,no_solicit_of_employees"task_kind = "single-contract-checklist"
[metadata.openenv_hf_sandbox]variant = "apex-gap-hfsandbox-v1"task_modified_for_hf_sandbox = truenetwork_enabled = true
[environment]docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf"workdir = "/workspace"cpus = 1memory_mb = 4096build_timeout_sec = 600network_mode = "public"
[agent]timeout_sec = 1800network_mode = "public"
[verifier]timeout_sec = 600network_mode = "public"environment_mode = "separate"
[verifier.environment]network_mode = "public"cpus = 1memory_mb = 4096
[[artifacts]]source = "/workspace/outputs"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960{ "checks": [ { "id": "agreement_date", "type": "answer", "field": "agreement_date", "kind": "date", "value": "2005-06-01" }, { "id": "exclusivity", "type": "answer", "field": "exclusivity", "kind": "bool", "value": true }, { "id": "most_favored_nation", "type": "answer", "field": "most_favored_nation", "kind": "bool", "value": false }, { "id": "audit_rights", "type": "answer", "field": "audit_rights", "kind": "bool", "value": true }, { "id": "ip_ownership_assignment", "type": "answer", "field": "ip_ownership_assignment", "kind": "bool", "value": true }, { "id": "liquidated_damages", "type": "answer", "field": "liquidated_damages", "kind": "bool", "value": true }, { "id": "source_code_escrow", "type": "answer", "field": "source_code_escrow", "kind": "bool", "value": false }, { "id": "no_solicit_of_employees", "type": "answer", "field": "no_solicit_of_employees", "kind": "bool", "value": false } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330"""Deterministic grader shared by converted knowledge-work tasks.
Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects thesubmitted /workspace/outputs tree and writes a binary reward plus per-check details.No model calls and no network.
expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]}Check types: answer field of outputs/answer.json; kind = number|text|choice|date|bool|list xlsx_range recalculated outputs/<file> vs tests/<target> over sheet!range (SpreadsheetBench rules) xlsx_cell recalculated outputs/<file> sheet!cell vs value with tolerance (optional alt_values) file_contains outputs/<file> text (docx/pdf/ics/eml/txt) must contain every needle custom tests/<module>.py defines check(spec, outputs_dir, tests_dir) -> (bool, str)"""
import datetime as dtimport jsonimport reimport shutilimport subprocessimport sysimport tempfileimport unicodedatafrom pathlib import Path
OUT = Path("/workspace/outputs")TESTS = Path("/tests")LOGS = Path("/logs/verifier")
def norm_text(v): v = unicodedata.normalize("NFKC", str(v)).casefold() v = re.sub(r"[‘’“”]", "'", v) v = re.sub(r"[^\w%.$/-]+", " ", v) return " ".join(v.split()).strip(" .")
def to_number(v): if isinstance(v, bool): raise ValueError("bool") if isinstance(v, (int, float)): return float(v) s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") neg = s.startswith("(") and s.endswith(")") s = s.strip("()").strip() pct = s.endswith("%") s = s.rstrip("%").strip() s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) x = float(s) x = -x if neg else x return x / 100 if pct else x
def number_ok(got, want, rel, abs_): try: g = to_number(got) except (TypeError, ValueError): return False w = float(want) tol = max(abs_, rel * abs(w)) # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] return any(abs(c - w) <= tol for c in candidates)
def parse_date(v): if isinstance(v, (dt.date, dt.datetime)): return v if isinstance(v, dt.date) else v.date() s = str(v).strip() for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): try: return dt.datetime.strptime(s, fmt).date() except ValueError: continue raise ValueError(s)
def check_answer(check, answers): key = check["field"] if key not in answers: return False, f"missing field {key!r}" got, want, kind = answers[key], check["value"], check.get("kind", "text") if kind == "number": ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) if not ok and check.get("percent_either"): ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) ) elif kind == "date": try: ok = parse_date(got) == parse_date(want) except ValueError: ok = False elif kind == "bool": g = norm_text(got) ok = g in {"yes", "true"} if want else g in {"no", "false"} elif kind == "choice": ok = norm_text(got) == norm_text(want) elif kind == "list": if not isinstance(got, list): return False, f"{key}: expected a JSON list" # Filenames may be given with a directory prefix; compare base names. base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) else: accepted = check.get("accept", [want]) ok = norm_text(got) in {norm_text(a) for a in accepted} return ok, "" if ok else f"{key}: got {got!r}"
# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation.RECALC_PROFILE = """<?xml version="1.0" encoding="UTF-8"?><oor:items xmlns:oor="http://openoffice.org/2001/registry" xmlns:xs="http://www.w3.org/2001/XMLSchema"><item oor:path="/org.openoffice.Office.Calc/Formula/Load"><prop oor:name="OOXMLRecalcMode" oor:op="fuse"><value>0</value></prop></item><item oor:path="/org.openoffice.Office.Calc/Formula/Load"><prop oor:name="ODFRecalcMode" oor:op="fuse"><value>0</value></prop></item></oor:items>"""
def recalc(path, tmp): dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" dest.mkdir() profile = Path(tmp) / "lo-profile" if not profile.exists(): (profile / "user").mkdir(parents=True) (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) subprocess.run( ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=180, check=False, ) out = dest / (Path(path).stem + ".xlsx") return out if out.exists() else Path(path)
def cell_value(v): if isinstance(v, (int, float)) and not isinstance(v, bool): return round(float(v), 2) if isinstance(v, dt.datetime): return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) if isinstance(v, dt.time): return v.strftime("%H:%M") if isinstance(v, str): try: return round(float(v), 2) except ValueError: return v.strip() return v
def time_of(v): """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" if isinstance(v, dt.time): v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") return None
def same_cell(a, b): if isinstance(a, dt.time) is not isinstance(b, dt.time): n = b if isinstance(a, dt.time) else a if time_of(n) is not None: # a time against a plain day fraction return time_of(a) == time_of(b) a, b = cell_value(a), cell_value(b) if a in (None, "") and b in (None, ""): return True return type(a) is type(b) and a == b
ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"}
def is_error(v): return isinstance(v, str) and (v in ERRORS or v.startswith("Err:"))
def cells(rng): if ":" not in rng: return [rng] from openpyxl.utils import range_boundaries, get_column_letter
c1, r1, c2, r2 = range_boundaries(rng) return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)]
def load(path, tmp): import openpyxl
return openpyxl.load_workbook(recalc(path, tmp), data_only=True)
def check_xlsx_range(check, tmp, cache): sub = OUT / check["file"] if not sub.is_file(): return False, f"missing output {check['file']}" if sub not in cache: cache[sub] = load(sub, tmp) tgt = TESTS / check["target"] if tgt not in cache: cache[tgt] = load(tgt, tmp) got, want = cache[sub], cache[tgt] cached = None # the target's stored (Excel-computed) values, read only when Calc errs for sheet, rng in check["ranges"]: sheet = sheet or want.sheetnames[0] if sheet not in got.sheetnames: return False, f"sheet {sheet!r} missing" for name in cells(rng): w = want[sheet][name].value if is_error(w): # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). # The value Excel stored is the intended answer. if cached is None: import openpyxl
cached = openpyxl.load_workbook(tgt, data_only=True) c = cached[sheet][name].value if sheet in cached.sheetnames else None if c is not None and not is_error(c): w = c if not same_cell(w, got[sheet][name].value): return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" return True, ""
def check_xlsx_cell(check, tmp, cache): sub = OUT / check["file"] if not sub.is_file(): return False, f"missing output {check['file']}" if sub not in cache: cache[sub] = load(sub, tmp) wb = cache[sub] if check["sheet"] not in wb.sheetnames: return False, f"sheet {check['sheet']!r} missing" got = wb[check["sheet"]][check["cell"]].value want = check["value"] if isinstance(want, (int, float)): # alt_values: other accepted golds where the source admits more than one reading. ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) for w in [want, *check.get("alt_values", [])]) else: ok = norm_text(got) == norm_text(want) return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}"
def text_of(path): suffix = path.suffix.lower() if suffix == ".docx": import docx
d = docx.Document(path) parts = [p.text for p in d.paragraphs] for t in d.tables: parts += [c.text for row in t.rows for c in row.cells] return "\n".join(parts) if suffix == ".pdf": import pdfplumber
with pdfplumber.open(path) as pdf: return "\n".join(page.extract_text() or "" for page in pdf.pages) return path.read_text(errors="replace")
def check_file_contains(check, tmp, cache): sub = OUT / check["file"] if not sub.is_file(): return False, f"missing output {check['file']}" text = text_of(sub) hay = text if check.get("case_sensitive") else text.casefold() for needle in check["needles"]: n = needle if check.get("case_sensitive") else needle.casefold() if n not in hay: return False, f"{check['file']} lacks {needle!r}" return True, ""
def main(): LOGS.mkdir(parents=True, exist_ok=True) reward_path = LOGS / "reward.txt" reward_path.write_text("0\n") spec = json.loads((TESTS / "expected.json").read_text()) answers, details = {}, [] answer_file = OUT / "answer.json" if answer_file.is_file(): try: answers = json.loads(answer_file.read_text()) if not isinstance(answers, dict): answers = {} except json.JSONDecodeError: answers = {} tmp = tempfile.mkdtemp() cache = {} try: for check in spec["checks"]: try: if check["type"] == "answer": ok, why = check_answer(check, answers) elif check["type"] == "xlsx_range": ok, why = check_xlsx_range(check, tmp, cache) elif check["type"] == "xlsx_cell": ok, why = check_xlsx_cell(check, tmp, cache) elif check["type"] == "file_contains": ok, why = check_file_contains(check, tmp, cache) elif check["type"] == "custom": import importlib.util
spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") mod = importlib.util.module_from_spec(spec_) spec_.loader.exec_module(mod) ok, why = mod.check(check, OUT, TESTS) else: ok, why = False, f"unknown check type {check['type']}" except Exception as exc: # a malformed submission fails the check, not the grader ok, why = False, f"{type(exc).__name__}: {exc}" details.append({"id": check["id"], "passed": ok, "detail": why}) finally: shutil.rmtree(tmp, ignore_errors=True) passed = sum(d["passed"] for d in details) total = len(details) reward = 1 if total and passed == total else 0 (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) reward_path.write_text(f"{reward}\n") print(f"{passed}/{total} checks passed; reward {reward}")
if __name__ == "__main__": sys.exit(main())1234#!/bin/shset -eumkdir -p /logs/verifier /workspace/outputsexec python3 -B -I /tests/grade.py1234567891011121314151617181920212223242526{ "profile": "harbor-semantic-v1", "reward_key": "reward", "reward": { "range": [ 0, 1 ], "oracle_tolerance": 0, "floor_margin": 0.1 }, "resources": { "cpu": 1, "memory_mb": 4096, "disk_mb": 10240, "episode_timeout_s": 1800 }, "types": { "tags": [ "knowledge-work", "legal-documents", "pdf-extraction" ] }, "requires_credentials": false}123version https://git-lfs.github.com/spec/v1oid sha256:d2fe1782e48ca203e5e9a287f8b81009ec4acd8db89c910304b03bd2d6b06909size 1252491234567891011121314151617181920212223You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/FTENETWORKS_INC_02_18_2016-EX-99.4-STRATEGIC_ALLIANCE_AGREEMENT.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer.
Answer formats:
- Dates are strings in `YYYY-MM-DD` form.- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise.- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales).
Checklist:
1. **Expiration date** (`expiration_date`): The date the initial term ends, before any renewal.2. **Anti-assignment** (`anti_assignment`): Consent or notice of a party is required if the contract is assigned to a third party.3. **Most favored nation** (`most_favored_nation`): If a third party gets better terms on the licensing or sale of the technology, goods or services in the contract, the buyer under this contract is entitled to those better terms.4. **Insurance** (`insurance`): One party must maintain insurance for the benefit of the counterparty.5. **Liquidated damages** (`liquidated_damages`): Either party can be awarded liquidated damages for breach, or a fee on termination of the contract (a termination fee).6. **Source code escrow** (`source_code_escrow`): One party must deposit its source code with a third-party escrow agent for release to the counterparty on certain events such as bankruptcy or insolvency.7. **Non-disparagement** (`non_disparagement`): A party must not disparage the counterparty.8. **Revenue or profit sharing** (`revenue_profit_sharing`): One party must share revenue or profit with the counterparty for any technology, goods or services.
## Deliverable
Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`expiration_date`, `anti_assignment`, `most_favored_nation`, `insurance`, `liquidated_damages`, `source_code_escrow`, `non_disparagement`, `revenue_profit_sharing`).12345678910{ "expiration_date": "2019-02-16", "anti_assignment": "Yes", "most_favored_nation": "No", "insurance": "Yes", "liquidated_damages": "Yes", "source_code_escrow": "No", "non_disparagement": "No", "revenue_profit_sharing": "No"}1234#!/bin/shset -eumkdir -p /workspace/outputscp -R /solution/files/. /workspace/outputs/1234567891011121314151617181920212223242526272829303132333435363738394041424344schema_version = "1.3"
[task]name = "apex-gap/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde"
[metadata.apex_gap]capability_tags = ["legal-documents", "pdf-extraction"]job = "corporate-law"source = "theatticusproject/cuad"source_license = "CC-BY-4.0"source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1"source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)"source_task_id = "FTENETWORKS,INC_02_18_2016-EX-99.4-STRATEGIC ALLIANCE AGREEMENT.PDF:expiration_date,anti_assignment,most_favored_nation,insurance,liquidated_damages,source_code_escrow,non_disparagement,revenue_profit_sharing"task_kind = "single-contract-checklist"
[metadata.openenv_hf_sandbox]variant = "apex-gap-hfsandbox-v1"task_modified_for_hf_sandbox = truenetwork_enabled = true
[environment]docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf"workdir = "/workspace"cpus = 1memory_mb = 4096build_timeout_sec = 600network_mode = "public"
[agent]timeout_sec = 1800network_mode = "public"
[verifier]timeout_sec = 600network_mode = "public"environment_mode = "separate"
[verifier.environment]network_mode = "public"cpus = 1memory_mb = 4096
[[artifacts]]source = "/workspace/outputs"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960{ "checks": [ { "id": "expiration_date", "type": "answer", "field": "expiration_date", "kind": "date", "value": "2019-02-16" }, { "id": "anti_assignment", "type": "answer", "field": "anti_assignment", "kind": "bool", "value": true }, { "id": "most_favored_nation", "type": "answer", "field": "most_favored_nation", "kind": "bool", "value": false }, { "id": "insurance", "type": "answer", "field": "insurance", "kind": "bool", "value": true }, { "id": "liquidated_damages", "type": "answer", "field": "liquidated_damages", "kind": "bool", "value": true }, { "id": "source_code_escrow", "type": "answer", "field": "source_code_escrow", "kind": "bool", "value": false }, { "id": "non_disparagement", "type": "answer", "field": "non_disparagement", "kind": "bool", "value": false }, { "id": "revenue_profit_sharing", "type": "answer", "field": "revenue_profit_sharing", "kind": "bool", "value": false } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330"""Deterministic grader shared by converted knowledge-work tasks.
Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects thesubmitted /workspace/outputs tree and writes a binary reward plus per-check details.No model calls and no network.
expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]}Check types: answer field of outputs/answer.json; kind = number|text|choice|date|bool|list xlsx_range recalculated outputs/<file> vs tests/<target> over sheet!range (SpreadsheetBench rules) xlsx_cell recalculated outputs/<file> sheet!cell vs value with tolerance (optional alt_values) file_contains outputs/<file> text (docx/pdf/ics/eml/txt) must contain every needle custom tests/<module>.py defines check(spec, outputs_dir, tests_dir) -> (bool, str)"""
import datetime as dtimport jsonimport reimport shutilimport subprocessimport sysimport tempfileimport unicodedatafrom pathlib import Path
OUT = Path("/workspace/outputs")TESTS = Path("/tests")LOGS = Path("/logs/verifier")
def norm_text(v): v = unicodedata.normalize("NFKC", str(v)).casefold() v = re.sub(r"[‘’“”]", "'", v) v = re.sub(r"[^\w%.$/-]+", " ", v) return " ".join(v.split()).strip(" .")
def to_number(v): if isinstance(v, bool): raise ValueError("bool") if isinstance(v, (int, float)): return float(v) s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") neg = s.startswith("(") and s.endswith(")") s = s.strip("()").strip() pct = s.endswith("%") s = s.rstrip("%").strip() s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) x = float(s) x = -x if neg else x return x / 100 if pct else x
def number_ok(got, want, rel, abs_): try: g = to_number(got) except (TypeError, ValueError): return False w = float(want) tol = max(abs_, rel * abs(w)) # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] return any(abs(c - w) <= tol for c in candidates)
def parse_date(v): if isinstance(v, (dt.date, dt.datetime)): return v if isinstance(v, dt.date) else v.date() s = str(v).strip() for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): try: return dt.datetime.strptime(s, fmt).date() except ValueError: continue raise ValueError(s)
def check_answer(check, answers): key = check["field"] if key not in answers: return False, f"missing field {key!r}" got, want, kind = answers[key], check["value"], check.get("kind", "text") if kind == "number": ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) if not ok and check.get("percent_either"): ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) ) elif kind == "date": try: ok = parse_date(got) == parse_date(want) except ValueError: ok = False elif kind == "bool": g = norm_text(got) ok = g in {"yes", "true"} if want else g in {"no", "false"} elif kind == "choice": ok = norm_text(got) == norm_text(want) elif kind == "list": if not isinstance(got, list): return False, f"{key}: expected a JSON list" # Filenames may be given with a directory prefix; compare base names. base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) else: accepted = check.get("accept", [want]) ok = norm_text(got) in {norm_text(a) for a in accepted} return ok, "" if ok else f"{key}: got {got!r}"
# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation.RECALC_PROFILE = """<?xml version="1.0" encoding="UTF-8"?><oor:items xmlns:oor="http://openoffice.org/2001/registry" xmlns:xs="http://www.w3.org/2001/XMLSchema"><item oor:path="/org.openoffice.Office.Calc/Formula/Load"><prop oor:name="OOXMLRecalcMode" oor:op="fuse"><value>0</value></prop></item><item oor:path="/org.openoffice.Office.Calc/Formula/Load"><prop oor:name="ODFRecalcMode" oor:op="fuse"><value>0</value></prop></item></oor:items>"""
def recalc(path, tmp): dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" dest.mkdir() profile = Path(tmp) / "lo-profile" if not profile.exists(): (profile / "user").mkdir(parents=True) (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) subprocess.run( ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=180, check=False, ) out = dest / (Path(path).stem + ".xlsx") return out if out.exists() else Path(path)
def cell_value(v): if isinstance(v, (int, float)) and not isinstance(v, bool): return round(float(v), 2) if isinstance(v, dt.datetime): return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) if isinstance(v, dt.time): return v.strftime("%H:%M") if isinstance(v, str): try: return round(float(v), 2) except ValueError: return v.strip() return v
def time_of(v): """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" if isinstance(v, dt.time): v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") return None
def same_cell(a, b): if isinstance(a, dt.time) is not isinstance(b, dt.time): n = b if isinstance(a, dt.time) else a if time_of(n) is not None: # a time against a plain day fraction return time_of(a) == time_of(b) a, b = cell_value(a), cell_value(b) if a in (None, "") and b in (None, ""): return True return type(a) is type(b) and a == b
ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"}
def is_error(v): return isinstance(v, str) and (v in ERRORS or v.startswith("Err:"))
def cells(rng): if ":" not in rng: return [rng] from openpyxl.utils import range_boundaries, get_column_letter
c1, r1, c2, r2 = range_boundaries(rng) return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)]
def load(path, tmp): import openpyxl
return openpyxl.load_workbook(recalc(path, tmp), data_only=True)
def check_xlsx_range(check, tmp, cache): sub = OUT / check["file"] if not sub.is_file(): return False, f"missing output {check['file']}" if sub not in cache: cache[sub] = load(sub, tmp) tgt = TESTS / check["target"] if tgt not in cache: cache[tgt] = load(tgt, tmp) got, want = cache[sub], cache[tgt] cached = None # the target's stored (Excel-computed) values, read only when Calc errs for sheet, rng in check["ranges"]: sheet = sheet or want.sheetnames[0] if sheet not in got.sheetnames: return False, f"sheet {sheet!r} missing" for name in cells(rng): w = want[sheet][name].value if is_error(w): # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). # The value Excel stored is the intended answer. if cached is None: import openpyxl
cached = openpyxl.load_workbook(tgt, data_only=True) c = cached[sheet][name].value if sheet in cached.sheetnames else None if c is not None and not is_error(c): w = c if not same_cell(w, got[sheet][name].value): return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" return True, ""
def check_xlsx_cell(check, tmp, cache): sub = OUT / check["file"] if not sub.is_file(): return False, f"missing output {check['file']}" if sub not in cache: cache[sub] = load(sub, tmp) wb = cache[sub] if check["sheet"] not in wb.sheetnames: return False, f"sheet {check['sheet']!r} missing" got = wb[check["sheet"]][check["cell"]].value want = check["value"] if isinstance(want, (int, float)): # alt_values: other accepted golds where the source admits more than one reading. ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) for w in [want, *check.get("alt_values", [])]) else: ok = norm_text(got) == norm_text(want) return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}"
def text_of(path): suffix = path.suffix.lower() if suffix == ".docx": import docx
d = docx.Document(path) parts = [p.text for p in d.paragraphs] for t in d.tables: parts += [c.text for row in t.rows for c in row.cells] return "\n".join(parts) if suffix == ".pdf": import pdfplumber
with pdfplumber.open(path) as pdf: return "\n".join(page.extract_text() or "" for page in pdf.pages) return path.read_text(errors="replace")
def check_file_contains(check, tmp, cache): sub = OUT / check["file"] if not sub.is_file(): return False, f"missing output {check['file']}" text = text_of(sub) hay = text if check.get("case_sensitive") else text.casefold() for needle in check["needles"]: n = needle if check.get("case_sensitive") else needle.casefold() if n not in hay: return False, f"{check['file']} lacks {needle!r}" return True, ""
def main(): LOGS.mkdir(parents=True, exist_ok=True) reward_path = LOGS / "reward.txt" reward_path.write_text("0\n") spec = json.loads((TESTS / "expected.json").read_text()) answers, details = {}, [] answer_file = OUT / "answer.json" if answer_file.is_file(): try: answers = json.loads(answer_file.read_text()) if not isinstance(answers, dict): answers = {} except json.JSONDecodeError: answers = {} tmp = tempfile.mkdtemp() cache = {} try: for check in spec["checks"]: try: if check["type"] == "answer": ok, why = check_answer(check, answers) elif check["type"] == "xlsx_range": ok, why = check_xlsx_range(check, tmp, cache) elif check["type"] == "xlsx_cell": ok, why = check_xlsx_cell(check, tmp, cache) elif check["type"] == "file_contains": ok, why = check_file_contains(check, tmp, cache) elif check["type"] == "custom": import importlib.util
spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") mod = importlib.util.module_from_spec(spec_) spec_.loader.exec_module(mod) ok, why = mod.check(check, OUT, TESTS) else: ok, why = False, f"unknown check type {check['type']}" except Exception as exc: # a malformed submission fails the check, not the grader ok, why = False, f"{type(exc).__name__}: {exc}" details.append({"id": check["id"], "passed": ok, "detail": why}) finally: shutil.rmtree(tmp, ignore_errors=True) passed = sum(d["passed"] for d in details) total = len(details) reward = 1 if total and passed == total else 0 (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) reward_path.write_text(f"{reward}\n") print(f"{passed}/{total} checks passed; reward {reward}")
if __name__ == "__main__": sys.exit(main())1234#!/bin/shset -eumkdir -p /logs/verifier /workspace/outputsexec python3 -B -I /tests/grade.py1234567891011121314151617181920212223242526{ "profile": "harbor-semantic-v1", "reward_key": "reward", "reward": { "range": [ 0, 1 ], "oracle_tolerance": 0, "floor_margin": 0.1 }, "resources": { "cpu": 1, "memory_mb": 4096, "disk_mb": 10240, "episode_timeout_s": 1800 }, "types": { "tags": [ "knowledge-work", "legal-documents", "pdf-extraction" ] }, "requires_credentials": false}123version https://git-lfs.github.com/spec/v1oid sha256:6a030ed8d8f65605e86f7e6e48316aa823800a0b5ece674ad7fea0147e1a00adsize 11026212345678910111213141516171819202122You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/FulucaiProductionsLtd_20131223_10-Q_EX-10.9_8368347_EX-10.9_Content_License_Agreement.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer.
Answer formats:
- Dates are strings in `YYYY-MM-DD` form.- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise.- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales).
Checklist:
1. **Agreement date** (`agreement_date`): The date of the contract: the date it is dated or entered into, as stated in the document.2. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract.3. **Exclusivity** (`exclusivity`): There is an exclusive dealing commitment with the counterparty: a commitment to procure all requirements from one party, or a prohibition on licensing or selling to third parties or on working with other parties, during or after the contract. An exclusive license, appointment or territory granted to the counterparty counts.4. **Termination for convenience** (`termination_for_convenience`): A party can terminate the contract without cause, solely by giving notice and letting a waiting period expire.5. **Most favored nation** (`most_favored_nation`): If a third party gets better terms on the licensing or sale of the technology, goods or services in the contract, the buyer under this contract is entitled to those better terms.6. **Audit rights** (`audit_rights`): A party has the right to audit the books, records or physical locations of the counterparty to check compliance with the contract.7. **Non-disparagement** (`non_disparagement`): A party must not disparage the counterparty.
## Deliverable
Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`agreement_date`, `governing_law`, `exclusivity`, `termination_for_convenience`, `most_favored_nation`, `audit_rights`, `non_disparagement`).123456789{ "agreement_date": "2012-11-15", "governing_law": "Florida", "exclusivity": "Yes", "termination_for_convenience": "No", "most_favored_nation": "No", "audit_rights": "Yes", "non_disparagement": "No"}1234#!/bin/shset -eumkdir -p /workspace/outputscp -R /solution/files/. /workspace/outputs/1234567891011121314151617181920212223242526272829303132333435363738394041424344schema_version = "1.3"
[task]name = "apex-gap/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31"
[metadata.apex_gap]capability_tags = ["legal-documents", "pdf-extraction"]job = "corporate-law"source = "theatticusproject/cuad"source_license = "CC-BY-4.0"source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1"source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)"source_task_id = "FulucaiProductionsLtd_20131223_10-Q_EX-10.9_8368347_EX-10.9_Content License Agreement.pdf:agreement_date,governing_law,exclusivity,termination_for_convenience,most_favored_nation,audit_rights,non_disparagement"task_kind = "single-contract-checklist"
[metadata.openenv_hf_sandbox]variant = "apex-gap-hfsandbox-v1"task_modified_for_hf_sandbox = truenetwork_enabled = true
[environment]docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf"workdir = "/workspace"cpus = 1memory_mb = 4096build_timeout_sec = 600network_mode = "public"
[agent]timeout_sec = 1800network_mode = "public"
[verifier]timeout_sec = 600network_mode = "public"environment_mode = "separate"
[verifier.environment]network_mode = "public"cpus = 1memory_mb = 4096
[[artifacts]]source = "/workspace/outputs"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859{ "checks": [ { "id": "agreement_date", "type": "answer", "field": "agreement_date", "kind": "date", "value": "2012-11-15" }, { "id": "governing_law", "type": "answer", "field": "governing_law", "kind": "text", "value": "Florida", "accept": [ "Florida", "State of Florida", "Florida, USA", "Florida, United States" ] }, { "id": "exclusivity", "type": "answer", "field": "exclusivity", "kind": "bool", "value": true }, { "id": "termination_for_convenience", "type": "answer", "field": "termination_for_convenience", "kind": "bool", "value": false }, { "id": "most_favored_nation", "type": "answer", "field": "most_favored_nation", "kind": "bool", "value": false }, { "id": "audit_rights", "type": "answer", "field": "audit_rights", "kind": "bool", "value": true }, { "id": "non_disparagement", "type": "answer", "field": "non_disparagement", "kind": "bool", "value": false } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330"""Deterministic grader shared by converted knowledge-work tasks.
Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects thesubmitted /workspace/outputs tree and writes a binary reward plus per-check details.No model calls and no network.
expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]}Check types: answer field of outputs/answer.json; kind = number|text|choice|date|bool|list xlsx_range recalculated outputs/<file> vs tests/<target> over sheet!range (SpreadsheetBench rules) xlsx_cell recalculated outputs/<file> sheet!cell vs value with tolerance (optional alt_values) file_contains outputs/<file> text (docx/pdf/ics/eml/txt) must contain every needle custom tests/<module>.py defines check(spec, outputs_dir, tests_dir) -> (bool, str)"""
import datetime as dtimport jsonimport reimport shutilimport subprocessimport sysimport tempfileimport unicodedatafrom pathlib import Path
OUT = Path("/workspace/outputs")TESTS = Path("/tests")LOGS = Path("/logs/verifier")
def norm_text(v): v = unicodedata.normalize("NFKC", str(v)).casefold() v = re.sub(r"[‘’“”]", "'", v) v = re.sub(r"[^\w%.$/-]+", " ", v) return " ".join(v.split()).strip(" .")
def to_number(v): if isinstance(v, bool): raise ValueError("bool") if isinstance(v, (int, float)): return float(v) s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") neg = s.startswith("(") and s.endswith(")") s = s.strip("()").strip() pct = s.endswith("%") s = s.rstrip("%").strip() s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) x = float(s) x = -x if neg else x return x / 100 if pct else x
def number_ok(got, want, rel, abs_): try: g = to_number(got) except (TypeError, ValueError): return False w = float(want) tol = max(abs_, rel * abs(w)) # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] return any(abs(c - w) <= tol for c in candidates)
def parse_date(v): if isinstance(v, (dt.date, dt.datetime)): return v if isinstance(v, dt.date) else v.date() s = str(v).strip() for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): try: return dt.datetime.strptime(s, fmt).date() except ValueError: continue raise ValueError(s)
def check_answer(check, answers): key = check["field"] if key not in answers: return False, f"missing field {key!r}" got, want, kind = answers[key], check["value"], check.get("kind", "text") if kind == "number": ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) if not ok and check.get("percent_either"): ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) ) elif kind == "date": try: ok = parse_date(got) == parse_date(want) except ValueError: ok = False elif kind == "bool": g = norm_text(got) ok = g in {"yes", "true"} if want else g in {"no", "false"} elif kind == "choice": ok = norm_text(got) == norm_text(want) elif kind == "list": if not isinstance(got, list): return False, f"{key}: expected a JSON list" # Filenames may be given with a directory prefix; compare base names. base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) else: accepted = check.get("accept", [want]) ok = norm_text(got) in {norm_text(a) for a in accepted} return ok, "" if ok else f"{key}: got {got!r}"
# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation.RECALC_PROFILE = """<?xml version="1.0" encoding="UTF-8"?><oor:items xmlns:oor="http://openoffice.org/2001/registry" xmlns:xs="http://www.w3.org/2001/XMLSchema"><item oor:path="/org.openoffice.Office.Calc/Formula/Load"><prop oor:name="OOXMLRecalcMode" oor:op="fuse"><value>0</value></prop></item><item oor:path="/org.openoffice.Office.Calc/Formula/Load"><prop oor:name="ODFRecalcMode" oor:op="fuse"><value>0</value></prop></item></oor:items>"""
def recalc(path, tmp): dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" dest.mkdir() profile = Path(tmp) / "lo-profile" if not profile.exists(): (profile / "user").mkdir(parents=True) (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) subprocess.run( ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=180, check=False, ) out = dest / (Path(path).stem + ".xlsx") return out if out.exists() else Path(path)
def cell_value(v): if isinstance(v, (int, float)) and not isinstance(v, bool): return round(float(v), 2) if isinstance(v, dt.datetime): return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) if isinstance(v, dt.time): return v.strftime("%H:%M") if isinstance(v, str): try: return round(float(v), 2) except ValueError: return v.strip() return v
def time_of(v): """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" if isinstance(v, dt.time): v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") return None
def same_cell(a, b): if isinstance(a, dt.time) is not isinstance(b, dt.time): n = b if isinstance(a, dt.time) else a if time_of(n) is not None: # a time against a plain day fraction return time_of(a) == time_of(b) a, b = cell_value(a), cell_value(b) if a in (None, "") and b in (None, ""): return True return type(a) is type(b) and a == b
ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"}
def is_error(v): return isinstance(v, str) and (v in ERRORS or v.startswith("Err:"))
def cells(rng): if ":" not in rng: return [rng] from openpyxl.utils import range_boundaries, get_column_letter
c1, r1, c2, r2 = range_boundaries(rng) return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)]
def load(path, tmp): import openpyxl
return openpyxl.load_workbook(recalc(path, tmp), data_only=True)
def check_xlsx_range(check, tmp, cache): sub = OUT / check["file"] if not sub.is_file(): return False, f"missing output {check['file']}" if sub not in cache: cache[sub] = load(sub, tmp) tgt = TESTS / check["target"] if tgt not in cache: cache[tgt] = load(tgt, tmp) got, want = cache[sub], cache[tgt] cached = None # the target's stored (Excel-computed) values, read only when Calc errs for sheet, rng in check["ranges"]: sheet = sheet or want.sheetnames[0] if sheet not in got.sheetnames: return False, f"sheet {sheet!r} missing" for name in cells(rng): w = want[sheet][name].value if is_error(w): # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). # The value Excel stored is the intended answer. if cached is None: import openpyxl
cached = openpyxl.load_workbook(tgt, data_only=True) c = cached[sheet][name].value if sheet in cached.sheetnames else None if c is not None and not is_error(c): w = c if not same_cell(w, got[sheet][name].value): return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" return True, ""
def check_xlsx_cell(check, tmp, cache): sub = OUT / check["file"] if not sub.is_file(): return False, f"missing output {check['file']}" if sub not in cache: cache[sub] = load(sub, tmp) wb = cache[sub] if check["sheet"] not in wb.sheetnames: return False, f"sheet {check['sheet']!r} missing" got = wb[check["sheet"]][check["cell"]].value want = check["value"] if isinstance(want, (int, float)): # alt_values: other accepted golds where the source admits more than one reading. ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) for w in [want, *check.get("alt_values", [])]) else: ok = norm_text(got) == norm_text(want) return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}"
def text_of(path): suffix = path.suffix.lower() if suffix == ".docx": import docx
d = docx.Document(path) parts = [p.text for p in d.paragraphs] for t in d.tables: parts += [c.text for row in t.rows for c in row.cells] return "\n".join(parts) if suffix == ".pdf": import pdfplumber
with pdfplumber.open(path) as pdf: return "\n".join(page.extract_text() or "" for page in pdf.pages) return path.read_text(errors="replace")
def check_file_contains(check, tmp, cache): sub = OUT / check["file"] if not sub.is_file(): return False, f"missing output {check['file']}" text = text_of(sub) hay = text if check.get("case_sensitive") else text.casefold() for needle in check["needles"]: n = needle if check.get("case_sensitive") else needle.casefold() if n not in hay: return False, f"{check['file']} lacks {needle!r}" return True, ""
def main(): LOGS.mkdir(parents=True, exist_ok=True) reward_path = LOGS / "reward.txt" reward_path.write_text("0\n") spec = json.loads((TESTS / "expected.json").read_text()) answers, details = {}, [] answer_file = OUT / "answer.json" if answer_file.is_file(): try: answers = json.loads(answer_file.read_text()) if not isinstance(answers, dict): answers = {} except json.JSONDecodeError: answers = {} tmp = tempfile.mkdtemp() cache = {} try: for check in spec["checks"]: try: if check["type"] == "answer": ok, why = check_answer(check, answers) elif check["type"] == "xlsx_range": ok, why = check_xlsx_range(check, tmp, cache) elif check["type"] == "xlsx_cell": ok, why = check_xlsx_cell(check, tmp, cache) elif check["type"] == "file_contains": ok, why = check_file_contains(check, tmp, cache) elif check["type"] == "custom": import importlib.util
spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") mod = importlib.util.module_from_spec(spec_) spec_.loader.exec_module(mod) ok, why = mod.check(check, OUT, TESTS) else: ok, why = False, f"unknown check type {check['type']}" except Exception as exc: # a malformed submission fails the check, not the grader ok, why = False, f"{type(exc).__name__}: {exc}" details.append({"id": check["id"], "passed": ok, "detail": why}) finally: shutil.rmtree(tmp, ignore_errors=True) passed = sum(d["passed"] for d in details) total = len(details) reward = 1 if total and passed == total else 0 (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) reward_path.write_text(f"{reward}\n") print(f"{passed}/{total} checks passed; reward {reward}")
if __name__ == "__main__": sys.exit(main())1234#!/bin/shset -eumkdir -p /logs/verifier /workspace/outputsexec python3 -B -I /tests/grade.py1234567891011121314151617181920212223242526{ "profile": "harbor-semantic-v1", "reward_key": "reward", "reward": { "range": [ 0, 1 ], "oracle_tolerance": 0, "floor_margin": 0.1 }, "resources": { "cpu": 1, "memory_mb": 4096, "disk_mb": 10240, "episode_timeout_s": 1800 }, "types": { "tags": [ "knowledge-work", "legal-documents", "pdf-extraction" ] }, "requires_credentials": false}123version https://git-lfs.github.com/spec/v1oid sha256:b668fc77aeeae09a02221d0032814a43c160b5d5b4ab2a1ab9915a73e567f525size 2034651234567891011121314151617181920212223You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/GlobalTechnologiesGroupInc_20050928_10KSB_EX-10.9_4148808_EX-10.9_Content_License_Agreement.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer.
Answer formats:
- Dates are strings in `YYYY-MM-DD` form.- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise.- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales).
Checklist:
1. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract.2. **Anti-assignment** (`anti_assignment`): Consent or notice of a party is required if the contract is assigned to a third party.3. **Cap on liability** (`cap_on_liability`): The contract limits a party's liability for breach: a maximum recoverable amount, an exclusion of categories of damages (for example indirect, consequential or lost-profit damages), or a time limit for the counterparty to bring claims.4. **Most favored nation** (`most_favored_nation`): If a third party gets better terms on the licensing or sale of the technology, goods or services in the contract, the buyer under this contract is entitled to those better terms.5. **Audit rights** (`audit_rights`): A party has the right to audit the books, records or physical locations of the counterparty to check compliance with the contract.6. **Liquidated damages** (`liquidated_damages`): Either party can be awarded liquidated damages for breach, or a fee on termination of the contract (a termination fee).7. **Source code escrow** (`source_code_escrow`): One party must deposit its source code with a third-party escrow agent for release to the counterparty on certain events such as bankruptcy or insolvency.8. **License grant** (`license_grant`): One party grants a license to its counterparty.
## Deliverable
Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`governing_law`, `anti_assignment`, `cap_on_liability`, `most_favored_nation`, `audit_rights`, `liquidated_damages`, `source_code_escrow`, `license_grant`).12345678910{ "governing_law": "Florida", "anti_assignment": "Yes", "cap_on_liability": "Yes", "most_favored_nation": "No", "audit_rights": "No", "liquidated_damages": "No", "source_code_escrow": "No", "license_grant": "Yes"}1234#!/bin/shset -eumkdir -p /workspace/outputscp -R /solution/files/. /workspace/outputs/1234567891011121314151617181920212223242526272829303132333435363738394041424344schema_version = "1.3"
[task]name = "apex-gap/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8"
[metadata.apex_gap]capability_tags = ["legal-documents", "pdf-extraction"]job = "corporate-law"source = "theatticusproject/cuad"source_license = "CC-BY-4.0"source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1"source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)"source_task_id = "GlobalTechnologiesGroupInc_20050928_10KSB_EX-10.9_4148808_EX-10.9_Content License Agreement.pdf:governing_law,anti_assignment,cap_on_liability,most_favored_nation,audit_rights,liquidated_damages,source_code_escrow,license_grant"task_kind = "single-contract-checklist"
[metadata.openenv_hf_sandbox]variant = "apex-gap-hfsandbox-v1"task_modified_for_hf_sandbox = truenetwork_enabled = true
[environment]docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf"workdir = "/workspace"cpus = 1memory_mb = 4096build_timeout_sec = 600network_mode = "public"
[agent]timeout_sec = 1800network_mode = "public"
[verifier]timeout_sec = 600network_mode = "public"environment_mode = "separate"
[verifier.environment]network_mode = "public"cpus = 1memory_mb = 4096
[[artifacts]]source = "/workspace/outputs"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566{ "checks": [ { "id": "governing_law", "type": "answer", "field": "governing_law", "kind": "text", "value": "Florida", "accept": [ "Florida", "State of Florida", "Florida, USA", "Florida, United States" ] }, { "id": "anti_assignment", "type": "answer", "field": "anti_assignment", "kind": "bool", "value": true }, { "id": "cap_on_liability", "type": "answer", "field": "cap_on_liability", "kind": "bool", "value": true }, { "id": "most_favored_nation", "type": "answer", "field": "most_favored_nation", "kind": "bool", "value": false }, { "id": "audit_rights", "type": "answer", "field": "audit_rights", "kind": "bool", "value": false }, { "id": "liquidated_damages", "type": "answer", "field": "liquidated_damages", "kind": "bool", "value": false }, { "id": "source_code_escrow", "type": "answer", "field": "source_code_escrow", "kind": "bool", "value": false }, { "id": "license_grant", "type": "answer", "field": "license_grant", "kind": "bool", "value": true } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330"""Deterministic grader shared by converted knowledge-work tasks.
Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects thesubmitted /workspace/outputs tree and writes a binary reward plus per-check details.No model calls and no network.
expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]}Check types: answer field of outputs/answer.json; kind = number|text|choice|date|bool|list xlsx_range recalculated outputs/<file> vs tests/<target> over sheet!range (SpreadsheetBench rules) xlsx_cell recalculated outputs/<file> sheet!cell vs value with tolerance (optional alt_values) file_contains outputs/<file> text (docx/pdf/ics/eml/txt) must contain every needle custom tests/<module>.py defines check(spec, outputs_dir, tests_dir) -> (bool, str)"""
import datetime as dtimport jsonimport reimport shutilimport subprocessimport sysimport tempfileimport unicodedatafrom pathlib import Path
OUT = Path("/workspace/outputs")TESTS = Path("/tests")LOGS = Path("/logs/verifier")
def norm_text(v): v = unicodedata.normalize("NFKC", str(v)).casefold() v = re.sub(r"[‘’“”]", "'", v) v = re.sub(r"[^\w%.$/-]+", " ", v) return " ".join(v.split()).strip(" .")
def to_number(v): if isinstance(v, bool): raise ValueError("bool") if isinstance(v, (int, float)): return float(v) s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") neg = s.startswith("(") and s.endswith(")") s = s.strip("()").strip() pct = s.endswith("%") s = s.rstrip("%").strip() s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) x = float(s) x = -x if neg else x return x / 100 if pct else x
def number_ok(got, want, rel, abs_): try: g = to_number(got) except (TypeError, ValueError): return False w = float(want) tol = max(abs_, rel * abs(w)) # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] return any(abs(c - w) <= tol for c in candidates)
def parse_date(v): if isinstance(v, (dt.date, dt.datetime)): return v if isinstance(v, dt.date) else v.date() s = str(v).strip() for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): try: return dt.datetime.strptime(s, fmt).date() except ValueError: continue raise ValueError(s)
def check_answer(check, answers): key = check["field"] if key not in answers: return False, f"missing field {key!r}" got, want, kind = answers[key], check["value"], check.get("kind", "text") if kind == "number": ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) if not ok and check.get("percent_either"): ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) ) elif kind == "date": try: ok = parse_date(got) == parse_date(want) except ValueError: ok = False elif kind == "bool": g = norm_text(got) ok = g in {"yes", "true"} if want else g in {"no", "false"} elif kind == "choice": ok = norm_text(got) == norm_text(want) elif kind == "list": if not isinstance(got, list): return False, f"{key}: expected a JSON list" # Filenames may be given with a directory prefix; compare base names. base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) else: accepted = check.get("accept", [want]) ok = norm_text(got) in {norm_text(a) for a in accepted} return ok, "" if ok else f"{key}: got {got!r}"
# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation.RECALC_PROFILE = """<?xml version="1.0" encoding="UTF-8"?><oor:items xmlns:oor="http://openoffice.org/2001/registry" xmlns:xs="http://www.w3.org/2001/XMLSchema"><item oor:path="/org.openoffice.Office.Calc/Formula/Load"><prop oor:name="OOXMLRecalcMode" oor:op="fuse"><value>0</value></prop></item><item oor:path="/org.openoffice.Office.Calc/Formula/Load"><prop oor:name="ODFRecalcMode" oor:op="fuse"><value>0</value></prop></item></oor:items>"""
def recalc(path, tmp): dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" dest.mkdir() profile = Path(tmp) / "lo-profile" if not profile.exists(): (profile / "user").mkdir(parents=True) (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) subprocess.run( ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=180, check=False, ) out = dest / (Path(path).stem + ".xlsx") return out if out.exists() else Path(path)
def cell_value(v): if isinstance(v, (int, float)) and not isinstance(v, bool): return round(float(v), 2) if isinstance(v, dt.datetime): return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) if isinstance(v, dt.time): return v.strftime("%H:%M") if isinstance(v, str): try: return round(float(v), 2) except ValueError: return v.strip() return v
def time_of(v): """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" if isinstance(v, dt.time): v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") return None
def same_cell(a, b): if isinstance(a, dt.time) is not isinstance(b, dt.time): n = b if isinstance(a, dt.time) else a if time_of(n) is not None: # a time against a plain day fraction return time_of(a) == time_of(b) a, b = cell_value(a), cell_value(b) if a in (None, "") and b in (None, ""): return True return type(a) is type(b) and a == b
ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"}
def is_error(v): return isinstance(v, str) and (v in ERRORS or v.startswith("Err:"))
def cells(rng): if ":" not in rng: return [rng] from openpyxl.utils import range_boundaries, get_column_letter
c1, r1, c2, r2 = range_boundaries(rng) return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)]
def load(path, tmp): import openpyxl
return openpyxl.load_workbook(recalc(path, tmp), data_only=True)
def check_xlsx_range(check, tmp, cache): sub = OUT / check["file"] if not sub.is_file(): return False, f"missing output {check['file']}" if sub not in cache: cache[sub] = load(sub, tmp) tgt = TESTS / check["target"] if tgt not in cache: cache[tgt] = load(tgt, tmp) got, want = cache[sub], cache[tgt] cached = None # the target's stored (Excel-computed) values, read only when Calc errs for sheet, rng in check["ranges"]: sheet = sheet or want.sheetnames[0] if sheet not in got.sheetnames: return False, f"sheet {sheet!r} missing" for name in cells(rng): w = want[sheet][name].value if is_error(w): # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). # The value Excel stored is the intended answer. if cached is None: import openpyxl
cached = openpyxl.load_workbook(tgt, data_only=True) c = cached[sheet][name].value if sheet in cached.sheetnames else None if c is not None and not is_error(c): w = c if not same_cell(w, got[sheet][name].value): return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" return True, ""
def check_xlsx_cell(check, tmp, cache): sub = OUT / check["file"] if not sub.is_file(): return False, f"missing output {check['file']}" if sub not in cache: cache[sub] = load(sub, tmp) wb = cache[sub] if check["sheet"] not in wb.sheetnames: return False, f"sheet {check['sheet']!r} missing" got = wb[check["sheet"]][check["cell"]].value want = check["value"] if isinstance(want, (int, float)): # alt_values: other accepted golds where the source admits more than one reading. ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) for w in [want, *check.get("alt_values", [])]) else: ok = norm_text(got) == norm_text(want) return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}"
def text_of(path): suffix = path.suffix.lower() if suffix == ".docx": import docx
d = docx.Document(path) parts = [p.text for p in d.paragraphs] for t in d.tables: parts += [c.text for row in t.rows for c in row.cells] return "\n".join(parts) if suffix == ".pdf": import pdfplumber
with pdfplumber.open(path) as pdf: return "\n".join(page.extract_text() or "" for page in pdf.pages) return path.read_text(errors="replace")
def check_file_contains(check, tmp, cache): sub = OUT / check["file"] if not sub.is_file(): return False, f"missing output {check['file']}" text = text_of(sub) hay = text if check.get("case_sensitive") else text.casefold() for needle in check["needles"]: n = needle if check.get("case_sensitive") else needle.casefold() if n not in hay: return False, f"{check['file']} lacks {needle!r}" return True, ""
def main(): LOGS.mkdir(parents=True, exist_ok=True) reward_path = LOGS / "reward.txt" reward_path.write_text("0\n") spec = json.loads((TESTS / "expected.json").read_text()) answers, details = {}, [] answer_file = OUT / "answer.json" if answer_file.is_file(): try: answers = json.loads(answer_file.read_text()) if not isinstance(answers, dict): answers = {} except json.JSONDecodeError: answers = {} tmp = tempfile.mkdtemp() cache = {} try: for check in spec["checks"]: try: if check["type"] == "answer": ok, why = check_answer(check, answers) elif check["type"] == "xlsx_range": ok, why = check_xlsx_range(check, tmp, cache) elif check["type"] == "xlsx_cell": ok, why = check_xlsx_cell(check, tmp, cache) elif check["type"] == "file_contains": ok, why = check_file_contains(check, tmp, cache) elif check["type"] == "custom": import importlib.util
spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") mod = importlib.util.module_from_spec(spec_) spec_.loader.exec_module(mod) ok, why = mod.check(check, OUT, TESTS) else: ok, why = False, f"unknown check type {check['type']}" except Exception as exc: # a malformed submission fails the check, not the grader ok, why = False, f"{type(exc).__name__}: {exc}" details.append({"id": check["id"], "passed": ok, "detail": why}) finally: shutil.rmtree(tmp, ignore_errors=True) passed = sum(d["passed"] for d in details) total = len(details) reward = 1 if total and passed == total else 0 (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) reward_path.write_text(f"{reward}\n") print(f"{passed}/{total} checks passed; reward {reward}")
if __name__ == "__main__": sys.exit(main())1234#!/bin/shset -eumkdir -p /logs/verifier /workspace/outputsexec python3 -B -I /tests/grade.py1234567891011121314151617181920212223242526{ "profile": "harbor-semantic-v1", "reward_key": "reward", "reward": { "range": [ 0, 1 ], "oracle_tolerance": 0, "floor_margin": 0.1 }, "resources": { "cpu": 1, "memory_mb": 4096, "disk_mb": 10240, "episode_timeout_s": 1800 }, "types": { "tags": [ "knowledge-work", "legal-documents", "pdf-extraction" ] }, "requires_credentials": false}123version https://git-lfs.github.com/spec/v1oid sha256:fee1c562facd69bcb9d76c614d36fc83bf9d69f8299d6a2bdb83e09789807c93size 3279591234567891011121314151617181920212223You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/GluMobileInc_20070319_S-1A_EX-10.09_436630_EX-10.09_Content_License_Agreement1.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer.
Answer formats:
- Dates are strings in `YYYY-MM-DD` form.- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise.- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales).
Checklist:
1. **Expiration date** (`expiration_date`): The date the initial term ends, before any renewal.2. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract.3. **Cap on liability** (`cap_on_liability`): The contract limits a party's liability for breach: a maximum recoverable amount, an exclusion of categories of damages (for example indirect, consequential or lost-profit damages), or a time limit for the counterparty to bring claims.4. **Most favored nation** (`most_favored_nation`): If a third party gets better terms on the licensing or sale of the technology, goods or services in the contract, the buyer under this contract is entitled to those better terms.5. **Audit rights** (`audit_rights`): A party has the right to audit the books, records or physical locations of the counterparty to check compliance with the contract.6. **IP ownership assignment** (`ip_ownership_assignment`): Intellectual property created by one party becomes the property of the counterparty, under the contract terms or on the occurrence of certain events.7. **Insurance** (`insurance`): One party must maintain insurance for the benefit of the counterparty.8. **Revenue or profit sharing** (`revenue_profit_sharing`): One party must share revenue or profit with the counterparty for any technology, goods or services.
## Deliverable
Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`expiration_date`, `governing_law`, `cap_on_liability`, `most_favored_nation`, `audit_rights`, `ip_ownership_assignment`, `insurance`, `revenue_profit_sharing`).12345678910{ "expiration_date": "2006-12-31", "governing_law": "California", "cap_on_liability": "Yes", "most_favored_nation": "No", "audit_rights": "Yes", "ip_ownership_assignment": "Yes", "insurance": "No", "revenue_profit_sharing": "Yes"}1234#!/bin/shset -eumkdir -p /workspace/outputscp -R /solution/files/. /workspace/outputs/1234567891011121314151617181920212223242526272829303132333435363738394041424344schema_version = "1.3"
[task]name = "apex-gap/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff"
[metadata.apex_gap]capability_tags = ["legal-documents", "pdf-extraction"]job = "corporate-law"source = "theatticusproject/cuad"source_license = "CC-BY-4.0"source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1"source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)"source_task_id = "GluMobileInc_20070319_S-1A_EX-10.09_436630_EX-10.09_Content License Agreement1.pdf:expiration_date,governing_law,cap_on_liability,most_favored_nation,audit_rights,ip_ownership_assignment,insurance,revenue_profit_sharing"task_kind = "single-contract-checklist"
[metadata.openenv_hf_sandbox]variant = "apex-gap-hfsandbox-v1"task_modified_for_hf_sandbox = truenetwork_enabled = true
[environment]docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf"workdir = "/workspace"cpus = 1memory_mb = 4096build_timeout_sec = 600network_mode = "public"
[agent]timeout_sec = 1800network_mode = "public"
[verifier]timeout_sec = 600network_mode = "public"environment_mode = "separate"
[verifier.environment]network_mode = "public"cpus = 1memory_mb = 4096
[[artifacts]]source = "/workspace/outputs"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566{ "checks": [ { "id": "expiration_date", "type": "answer", "field": "expiration_date", "kind": "date", "value": "2006-12-31" }, { "id": "governing_law", "type": "answer", "field": "governing_law", "kind": "text", "value": "California", "accept": [ "California", "State of California", "California, USA", "California, United States" ] }, { "id": "cap_on_liability", "type": "answer", "field": "cap_on_liability", "kind": "bool", "value": true }, { "id": "most_favored_nation", "type": "answer", "field": "most_favored_nation", "kind": "bool", "value": false }, { "id": "audit_rights", "type": "answer", "field": "audit_rights", "kind": "bool", "value": true }, { "id": "ip_ownership_assignment", "type": "answer", "field": "ip_ownership_assignment", "kind": "bool", "value": true }, { "id": "insurance", "type": "answer", "field": "insurance", "kind": "bool", "value": false }, { "id": "revenue_profit_sharing", "type": "answer", "field": "revenue_profit_sharing", "kind": "bool", "value": true } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330"""Deterministic grader shared by converted knowledge-work tasks.
Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects thesubmitted /workspace/outputs tree and writes a binary reward plus per-check details.No model calls and no network.
expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]}Check types: answer field of outputs/answer.json; kind = number|text|choice|date|bool|list xlsx_range recalculated outputs/<file> vs tests/<target> over sheet!range (SpreadsheetBench rules) xlsx_cell recalculated outputs/<file> sheet!cell vs value with tolerance (optional alt_values) file_contains outputs/<file> text (docx/pdf/ics/eml/txt) must contain every needle custom tests/<module>.py defines check(spec, outputs_dir, tests_dir) -> (bool, str)"""
import datetime as dtimport jsonimport reimport shutilimport subprocessimport sysimport tempfileimport unicodedatafrom pathlib import Path
OUT = Path("/workspace/outputs")TESTS = Path("/tests")LOGS = Path("/logs/verifier")
def norm_text(v): v = unicodedata.normalize("NFKC", str(v)).casefold() v = re.sub(r"[‘’“”]", "'", v) v = re.sub(r"[^\w%.$/-]+", " ", v) return " ".join(v.split()).strip(" .")
def to_number(v): if isinstance(v, bool): raise ValueError("bool") if isinstance(v, (int, float)): return float(v) s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") neg = s.startswith("(") and s.endswith(")") s = s.strip("()").strip() pct = s.endswith("%") s = s.rstrip("%").strip() s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) x = float(s) x = -x if neg else x return x / 100 if pct else x
def number_ok(got, want, rel, abs_): try: g = to_number(got) except (TypeError, ValueError): return False w = float(want) tol = max(abs_, rel * abs(w)) # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] return any(abs(c - w) <= tol for c in candidates)
def parse_date(v): if isinstance(v, (dt.date, dt.datetime)): return v if isinstance(v, dt.date) else v.date() s = str(v).strip() for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): try: return dt.datetime.strptime(s, fmt).date() except ValueError: continue raise ValueError(s)
def check_answer(check, answers): key = check["field"] if key not in answers: return False, f"missing field {key!r}" got, want, kind = answers[key], check["value"], check.get("kind", "text") if kind == "number": ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) if not ok and check.get("percent_either"): ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) ) elif kind == "date": try: ok = parse_date(got) == parse_date(want) except ValueError: ok = False elif kind == "bool": g = norm_text(got) ok = g in {"yes", "true"} if want else g in {"no", "false"} elif kind == "choice": ok = norm_text(got) == norm_text(want) elif kind == "list": if not isinstance(got, list): return False, f"{key}: expected a JSON list" # Filenames may be given with a directory prefix; compare base names. base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) else: accepted = check.get("accept", [want]) ok = norm_text(got) in {norm_text(a) for a in accepted} return ok, "" if ok else f"{key}: got {got!r}"
# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation.RECALC_PROFILE = """<?xml version="1.0" encoding="UTF-8"?><oor:items xmlns:oor="http://openoffice.org/2001/registry" xmlns:xs="http://www.w3.org/2001/XMLSchema"><item oor:path="/org.openoffice.Office.Calc/Formula/Load"><prop oor:name="OOXMLRecalcMode" oor:op="fuse"><value>0</value></prop></item><item oor:path="/org.openoffice.Office.Calc/Formula/Load"><prop oor:name="ODFRecalcMode" oor:op="fuse"><value>0</value></prop></item></oor:items>"""
def recalc(path, tmp): dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" dest.mkdir() profile = Path(tmp) / "lo-profile" if not profile.exists(): (profile / "user").mkdir(parents=True) (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) subprocess.run( ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=180, check=False, ) out = dest / (Path(path).stem + ".xlsx") return out if out.exists() else Path(path)
def cell_value(v): if isinstance(v, (int, float)) and not isinstance(v, bool): return round(float(v), 2) if isinstance(v, dt.datetime): return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) if isinstance(v, dt.time): return v.strftime("%H:%M") if isinstance(v, str): try: return round(float(v), 2) except ValueError: return v.strip() return v
def time_of(v): """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" if isinstance(v, dt.time): v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") return None
def same_cell(a, b): if isinstance(a, dt.time) is not isinstance(b, dt.time): n = b if isinstance(a, dt.time) else a if time_of(n) is not None: # a time against a plain day fraction return time_of(a) == time_of(b) a, b = cell_value(a), cell_value(b) if a in (None, "") and b in (None, ""): return True return type(a) is type(b) and a == b
ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"}
def is_error(v): return isinstance(v, str) and (v in ERRORS or v.startswith("Err:"))
def cells(rng): if ":" not in rng: return [rng] from openpyxl.utils import range_boundaries, get_column_letter
c1, r1, c2, r2 = range_boundaries(rng) return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)]
def load(path, tmp): import openpyxl
return openpyxl.load_workbook(recalc(path, tmp), data_only=True)
def check_xlsx_range(check, tmp, cache): sub = OUT / check["file"] if not sub.is_file(): return False, f"missing output {check['file']}" if sub not in cache: cache[sub] = load(sub, tmp) tgt = TESTS / check["target"] if tgt not in cache: cache[tgt] = load(tgt, tmp) got, want = cache[sub], cache[tgt] cached = None # the target's stored (Excel-computed) values, read only when Calc errs for sheet, rng in check["ranges"]: sheet = sheet or want.sheetnames[0] if sheet not in got.sheetnames: return False, f"sheet {sheet!r} missing" for name in cells(rng): w = want[sheet][name].value if is_error(w): # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). # The value Excel stored is the intended answer. if cached is None: import openpyxl
cached = openpyxl.load_workbook(tgt, data_only=True) c = cached[sheet][name].value if sheet in cached.sheetnames else None if c is not None and not is_error(c): w = c if not same_cell(w, got[sheet][name].value): return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" return True, ""
def check_xlsx_cell(check, tmp, cache): sub = OUT / check["file"] if not sub.is_file(): return False, f"missing output {check['file']}" if sub not in cache: cache[sub] = load(sub, tmp) wb = cache[sub] if check["sheet"] not in wb.sheetnames: return False, f"sheet {check['sheet']!r} missing" got = wb[check["sheet"]][check["cell"]].value want = check["value"] if isinstance(want, (int, float)): # alt_values: other accepted golds where the source admits more than one reading. ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) for w in [want, *check.get("alt_values", [])]) else: ok = norm_text(got) == norm_text(want) return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}"
def text_of(path): suffix = path.suffix.lower() if suffix == ".docx": import docx
d = docx.Document(path) parts = [p.text for p in d.paragraphs] for t in d.tables: parts += [c.text for row in t.rows for c in row.cells] return "\n".join(parts) if suffix == ".pdf": import pdfplumber
with pdfplumber.open(path) as pdf: return "\n".join(page.extract_text() or "" for page in pdf.pages) return path.read_text(errors="replace")
def check_file_contains(check, tmp, cache): sub = OUT / check["file"] if not sub.is_file(): return False, f"missing output {check['file']}" text = text_of(sub) hay = text if check.get("case_sensitive") else text.casefold() for needle in check["needles"]: n = needle if check.get("case_sensitive") else needle.casefold() if n not in hay: return False, f"{check['file']} lacks {needle!r}" return True, ""
def main(): LOGS.mkdir(parents=True, exist_ok=True) reward_path = LOGS / "reward.txt" reward_path.write_text("0\n") spec = json.loads((TESTS / "expected.json").read_text()) answers, details = {}, [] answer_file = OUT / "answer.json" if answer_file.is_file(): try: answers = json.loads(answer_file.read_text()) if not isinstance(answers, dict): answers = {} except json.JSONDecodeError: answers = {} tmp = tempfile.mkdtemp() cache = {} try: for check in spec["checks"]: try: if check["type"] == "answer": ok, why = check_answer(check, answers) elif check["type"] == "xlsx_range": ok, why = check_xlsx_range(check, tmp, cache) elif check["type"] == "xlsx_cell": ok, why = check_xlsx_cell(check, tmp, cache) elif check["type"] == "file_contains": ok, why = check_file_contains(check, tmp, cache) elif check["type"] == "custom": import importlib.util
spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") mod = importlib.util.module_from_spec(spec_) spec_.loader.exec_module(mod) ok, why = mod.check(check, OUT, TESTS) else: ok, why = False, f"unknown check type {check['type']}" except Exception as exc: # a malformed submission fails the check, not the grader ok, why = False, f"{type(exc).__name__}: {exc}" details.append({"id": check["id"], "passed": ok, "detail": why}) finally: shutil.rmtree(tmp, ignore_errors=True) passed = sum(d["passed"] for d in details) total = len(details) reward = 1 if total and passed == total else 0 (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) reward_path.write_text(f"{reward}\n") print(f"{passed}/{total} checks passed; reward {reward}")
if __name__ == "__main__": sys.exit(main())1234#!/bin/shset -eumkdir -p /logs/verifier /workspace/outputsexec python3 -B -I /tests/grade.py1234567891011121314151617181920212223242526{ "profile": "harbor-semantic-v1", "reward_key": "reward", "reward": { "range": [ 0, 1 ], "oracle_tolerance": 0, "floor_margin": 0.1 }, "resources": { "cpu": 1, "memory_mb": 4096, "disk_mb": 10240, "episode_timeout_s": 1800 }, "types": { "tags": [ "knowledge-work", "legal-documents", "pdf-extraction" ] }, "requires_credentials": false}123version https://git-lfs.github.com/spec/v1oid sha256:dc8efd92da2f9edc2121eef659268eb2c4d3a6ca17db04c84bd72903ccb3f98fsize 17196712345678910111213141516171819202122You are a corporate associate running legal due diligence on a target company's material contracts. The contract under review is `/workspace/inputs/GOLDRESOURCECORP_12_11_2008-EX-10.1-STRATEGIC_ALLIANCE_AGREEMENT.pdf`. Read it and complete the checklist below. Each item names the JSON field that holds its answer.
Answer formats:
- Dates are strings in `YYYY-MM-DD` form.- Clause questions take the string `Yes` if the contract contains any clause matching the definition, for either party and even if subject to exceptions, and `No` otherwise.- Governing law is a string naming the jurisdiction: a US state by its name alone (for example `Delaware`), a Canadian province or Australian state as `Province, Country` (for example `Ontario, Canada`), and any other jurisdiction by country (for example `Germany`; use `England` for the law of England and Wales).
Checklist:
1. **Governing law** (`governing_law`): the jurisdiction whose law governs the contract.2. **Anti-assignment** (`anti_assignment`): Consent or notice of a party is required if the contract is assigned to a third party.3. **Non-compete** (`non_compete`): A party is restricted from competing with the counterparty or from operating in a certain geography, business or technology sector.4. **Most favored nation** (`most_favored_nation`): Does entering a later agreement with a third party entitle HOC to materially more favourable standstill terms under the strategic alliance?5. **Insurance** (`insurance`): Does the agreement require the Company to maintain liability insurance for a director nominated by HOC, subject to the conditions in Article 5?6. **Source code escrow** (`source_code_escrow`): One party must deposit its source code with a third-party escrow agent for release to the counterparty on certain events such as bankruptcy or insolvency.7. **Non-disparagement** (`non_disparagement`): A party must not disparage the counterparty.
## Deliverable
Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in`/workspace/outputs/`; only that directory is graded. Write `/workspace/outputs/answer.json`, a JSON object with exactly the fields listed in the checklist (`governing_law`, `anti_assignment`, `non_compete`, `most_favored_nation`, `insurance`, `source_code_escrow`, `non_disparagement`).123456789{ "governing_law": "New York", "anti_assignment": "Yes", "non_compete": "No", "most_favored_nation": "Yes", "insurance": "Yes", "source_code_escrow": "No", "non_disparagement": "No"}1234#!/bin/shset -eumkdir -p /workspace/outputscp -R /solution/files/. /workspace/outputs/1234567891011121314151617181920212223242526272829303132333435363738394041424344schema_version = "1.3"
[task]name = "apex-gap/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3"
[metadata.apex_gap]capability_tags = ["legal-documents", "pdf-extraction"]job = "corporate-law"source = "theatticusproject/cuad"source_license = "CC-BY-4.0"source_revision = "a3c393f5d103fd0c516374e4fdff676c8176dcb1"source_split = "train (cuad-qa@6d9a118fb629814c4384a1e63cfc84f5c01894b3 contract split)"source_task_id = "GOLDRESOURCECORP_12_11_2008-EX-10.1-STRATEGIC ALLIANCE AGREEMENT.PDF:governing_law,anti_assignment,non_compete,most_favored_nation,insurance,source_code_escrow,non_disparagement"task_kind = "single-contract-checklist"
[metadata.openenv_hf_sandbox]variant = "apex-gap-hfsandbox-v1"task_modified_for_hf_sandbox = truenetwork_enabled = true
[environment]docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf"workdir = "/workspace"cpus = 1memory_mb = 4096build_timeout_sec = 600network_mode = "public"
[agent]timeout_sec = 1800network_mode = "public"
[verifier]timeout_sec = 600network_mode = "public"environment_mode = "separate"
[verifier.environment]network_mode = "public"cpus = 1memory_mb = 4096
[[artifacts]]source = "/workspace/outputs"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859{ "checks": [ { "id": "governing_law", "type": "answer", "field": "governing_law", "kind": "text", "value": "New York", "accept": [ "New York", "State of New York", "New York, USA", "New York, United States" ] }, { "id": "anti_assignment", "type": "answer", "field": "anti_assignment", "kind": "bool", "value": true }, { "id": "non_compete", "type": "answer", "field": "non_compete", "kind": "bool", "value": false }, { "id": "most_favored_nation", "type": "answer", "field": "most_favored_nation", "kind": "bool", "value": true }, { "id": "insurance", "type": "answer", "field": "insurance", "kind": "bool", "value": true }, { "id": "source_code_escrow", "type": "answer", "field": "source_code_escrow", "kind": "bool", "value": false }, { "id": "non_disparagement", "type": "answer", "field": "non_disparagement", "kind": "bool", "value": false } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330"""Deterministic grader shared by converted knowledge-work tasks.
Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects thesubmitted /workspace/outputs tree and writes a binary reward plus per-check details.No model calls and no network.
expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]}Check types: answer field of outputs/answer.json; kind = number|text|choice|date|bool|list xlsx_range recalculated outputs/<file> vs tests/<target> over sheet!range (SpreadsheetBench rules) xlsx_cell recalculated outputs/<file> sheet!cell vs value with tolerance (optional alt_values) file_contains outputs/<file> text (docx/pdf/ics/eml/txt) must contain every needle custom tests/<module>.py defines check(spec, outputs_dir, tests_dir) -> (bool, str)"""
import datetime as dtimport jsonimport reimport shutilimport subprocessimport sysimport tempfileimport unicodedatafrom pathlib import Path
OUT = Path("/workspace/outputs")TESTS = Path("/tests")LOGS = Path("/logs/verifier")
def norm_text(v): v = unicodedata.normalize("NFKC", str(v)).casefold() v = re.sub(r"[‘’“”]", "'", v) v = re.sub(r"[^\w%.$/-]+", " ", v) return " ".join(v.split()).strip(" .")
def to_number(v): if isinstance(v, bool): raise ValueError("bool") if isinstance(v, (int, float)): return float(v) s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") neg = s.startswith("(") and s.endswith(")") s = s.strip("()").strip() pct = s.endswith("%") s = s.rstrip("%").strip() s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) x = float(s) x = -x if neg else x return x / 100 if pct else x
def number_ok(got, want, rel, abs_): try: g = to_number(got) except (TypeError, ValueError): return False w = float(want) tol = max(abs_, rel * abs(w)) # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] return any(abs(c - w) <= tol for c in candidates)
def parse_date(v): if isinstance(v, (dt.date, dt.datetime)): return v if isinstance(v, dt.date) else v.date() s = str(v).strip() for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): try: return dt.datetime.strptime(s, fmt).date() except ValueError: continue raise ValueError(s)
def check_answer(check, answers): key = check["field"] if key not in answers: return False, f"missing field {key!r}" got, want, kind = answers[key], check["value"], check.get("kind", "text") if kind == "number": ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) if not ok and check.get("percent_either"): ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) ) elif kind == "date": try: ok = parse_date(got) == parse_date(want) except ValueError: ok = False elif kind == "bool": g = norm_text(got) ok = g in {"yes", "true"} if want else g in {"no", "false"} elif kind == "choice": ok = norm_text(got) == norm_text(want) elif kind == "list": if not isinstance(got, list): return False, f"{key}: expected a JSON list" # Filenames may be given with a directory prefix; compare base names. base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) else: accepted = check.get("accept", [want]) ok = norm_text(got) in {norm_text(a) for a in accepted} return ok, "" if ok else f"{key}: got {got!r}"
# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation.RECALC_PROFILE = """<?xml version="1.0" encoding="UTF-8"?><oor:items xmlns:oor="http://openoffice.org/2001/registry" xmlns:xs="http://www.w3.org/2001/XMLSchema"><item oor:path="/org.openoffice.Office.Calc/Formula/Load"><prop oor:name="OOXMLRecalcMode" oor:op="fuse"><value>0</value></prop></item><item oor:path="/org.openoffice.Office.Calc/Formula/Load"><prop oor:name="ODFRecalcMode" oor:op="fuse"><value>0</value></prop></item></oor:items>"""
def recalc(path, tmp): dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" dest.mkdir() profile = Path(tmp) / "lo-profile" if not profile.exists(): (profile / "user").mkdir(parents=True) (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) subprocess.run( ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=180, check=False, ) out = dest / (Path(path).stem + ".xlsx") return out if out.exists() else Path(path)
def cell_value(v): if isinstance(v, (int, float)) and not isinstance(v, bool): return round(float(v), 2) if isinstance(v, dt.datetime): return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) if isinstance(v, dt.time): return v.strftime("%H:%M") if isinstance(v, str): try: return round(float(v), 2) except ValueError: return v.strip() return v
def time_of(v): """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" if isinstance(v, dt.time): v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") return None
def same_cell(a, b): if isinstance(a, dt.time) is not isinstance(b, dt.time): n = b if isinstance(a, dt.time) else a if time_of(n) is not None: # a time against a plain day fraction return time_of(a) == time_of(b) a, b = cell_value(a), cell_value(b) if a in (None, "") and b in (None, ""): return True return type(a) is type(b) and a == b
ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"}
def is_error(v): return isinstance(v, str) and (v in ERRORS or v.startswith("Err:"))
def cells(rng): if ":" not in rng: return [rng] from openpyxl.utils import range_boundaries, get_column_letter
c1, r1, c2, r2 = range_boundaries(rng) return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)]
def load(path, tmp): import openpyxl
return openpyxl.load_workbook(recalc(path, tmp), data_only=True)
def check_xlsx_range(check, tmp, cache): sub = OUT / check["file"] if not sub.is_file(): return False, f"missing output {check['file']}" if sub not in cache: cache[sub] = load(sub, tmp) tgt = TESTS / check["target"] if tgt not in cache: cache[tgt] = load(tgt, tmp) got, want = cache[sub], cache[tgt] cached = None # the target's stored (Excel-computed) values, read only when Calc errs for sheet, rng in check["ranges"]: sheet = sheet or want.sheetnames[0] if sheet not in got.sheetnames: return False, f"sheet {sheet!r} missing" for name in cells(rng): w = want[sheet][name].value if is_error(w): # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). # The value Excel stored is the intended answer. if cached is None: import openpyxl
cached = openpyxl.load_workbook(tgt, data_only=True) c = cached[sheet][name].value if sheet in cached.sheetnames else None if c is not None and not is_error(c): w = c if not same_cell(w, got[sheet][name].value): return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" return True, ""
def check_xlsx_cell(check, tmp, cache): sub = OUT / check["file"] if not sub.is_file(): return False, f"missing output {check['file']}" if sub not in cache: cache[sub] = load(sub, tmp) wb = cache[sub] if check["sheet"] not in wb.sheetnames: return False, f"sheet {check['sheet']!r} missing" got = wb[check["sheet"]][check["cell"]].value want = check["value"] if isinstance(want, (int, float)): # alt_values: other accepted golds where the source admits more than one reading. ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) for w in [want, *check.get("alt_values", [])]) else: ok = norm_text(got) == norm_text(want) return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}"
def text_of(path): suffix = path.suffix.lower() if suffix == ".docx": import docx
d = docx.Document(path) parts = [p.text for p in d.paragraphs] for t in d.tables: parts += [c.text for row in t.rows for c in row.cells] return "\n".join(parts) if suffix == ".pdf": import pdfplumber
with pdfplumber.open(path) as pdf: return "\n".join(page.extract_text() or "" for page in pdf.pages) return path.read_text(errors="replace")
def check_file_contains(check, tmp, cache): sub = OUT / check["file"] if not sub.is_file(): return False, f"missing output {check['file']}" text = text_of(sub) hay = text if check.get("case_sensitive") else text.casefold() for needle in check["needles"]: n = needle if check.get("case_sensitive") else needle.casefold() if n not in hay: return False, f"{check['file']} lacks {needle!r}" return True, ""
def main(): LOGS.mkdir(parents=True, exist_ok=True) reward_path = LOGS / "reward.txt" reward_path.write_text("0\n") spec = json.loads((TESTS / "expected.json").read_text()) answers, details = {}, [] answer_file = OUT / "answer.json" if answer_file.is_file(): try: answers = json.loads(answer_file.read_text()) if not isinstance(answers, dict): answers = {} except json.JSONDecodeError: answers = {} tmp = tempfile.mkdtemp() cache = {} try: for check in spec["checks"]: try: if check["type"] == "answer": ok, why = check_answer(check, answers) elif check["type"] == "xlsx_range": ok, why = check_xlsx_range(check, tmp, cache) elif check["type"] == "xlsx_cell": ok, why = check_xlsx_cell(check, tmp, cache) elif check["type"] == "file_contains": ok, why = check_file_contains(check, tmp, cache) elif check["type"] == "custom": import importlib.util
spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") mod = importlib.util.module_from_spec(spec_) spec_.loader.exec_module(mod) ok, why = mod.check(check, OUT, TESTS) else: ok, why = False, f"unknown check type {check['type']}" except Exception as exc: # a malformed submission fails the check, not the grader ok, why = False, f"{type(exc).__name__}: {exc}" details.append({"id": check["id"], "passed": ok, "detail": why}) finally: shutil.rmtree(tmp, ignore_errors=True) passed = sum(d["passed"] for d in details) total = len(details) reward = 1 if total and passed == total else 0 (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) reward_path.write_text(f"{reward}\n") print(f"{passed}/{total} checks passed; reward {reward}")
if __name__ == "__main__": sys.exit(main()).gitattributes+33
tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/solution/solve.shAdded+4
tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/task.tomlAdded+44
tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/tests/expected.jsonAdded+60
tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/tests/grade.pyAdded+330
tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/tests/test.shAdded+4
tasks/cuad-dd-fibrogeninc-10-01-2014-ex-10-11-collabor-10a96028/validation/openenv.jsonAdded+26
tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/environment/inputs/FTENETWORKS_INC_02_18_2016-EX-99.4-STRATEGIC_ALLIANCE_AGREEMENT.pdfAdded+3
tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/instruction.mdAdded+23
tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/solution/files/answer.jsonAdded+10
tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/solution/solve.shAdded+4
tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/task.tomlAdded+44
tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/tests/expected.jsonAdded+60
tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/tests/grade.pyAdded+330
tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/tests/test.shAdded+4
tasks/cuad-dd-ftenetworks-inc-02-18-2016-ex-99-4-strat-3263edde/validation/openenv.jsonAdded+26
tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/environment/inputs/FulucaiProductionsLtd_20131223_10-Q_EX-10.9_8368347_EX-10.9_Content_License_Agreement.pdfAdded+3
tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/instruction.mdAdded+22
tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/solution/files/answer.jsonAdded+9
tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/solution/solve.shAdded+4
tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/task.tomlAdded+44
tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/tests/expected.jsonAdded+59
tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/tests/grade.pyAdded+330
tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/tests/test.shAdded+4
tasks/cuad-dd-fulucaiproductionsltd-20131223-10-q-ex-1-f4941a31/validation/openenv.jsonAdded+26
tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/environment/inputs/GlobalTechnologiesGroupInc_20050928_10KSB_EX-10.9_4148808_EX-10.9_Content_License_Agreement.pdfAdded+3
tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/instruction.mdAdded+23
tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/solution/files/answer.jsonAdded+10
tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/solution/solve.shAdded+4
tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/task.tomlAdded+44
tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/tests/expected.jsonAdded+66
tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/tests/grade.pyAdded+330
tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/tests/test.shAdded+4
tasks/cuad-dd-globaltechnologiesgroupinc-20050928-10ks-8321c3b8/validation/openenv.jsonAdded+26
tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/environment/inputs/GluMobileInc_20070319_S-1A_EX-10.09_436630_EX-10.09_Content_License_Agreement1.pdfAdded+3
tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/instruction.mdAdded+23
tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/solution/files/answer.jsonAdded+10
tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/solution/solve.shAdded+4
tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/task.tomlAdded+44
tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/tests/expected.jsonAdded+66
tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/tests/grade.pyAdded+330
tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/tests/test.shAdded+4
tasks/cuad-dd-glumobileinc-20070319-s-1a-ex-10-09-4366-e73220ff/validation/openenv.jsonAdded+26
tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/environment/inputs/GOLDRESOURCECORP_12_11_2008-EX-10.1-STRATEGIC_ALLIANCE_AGREEMENT.pdfAdded+3
tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/instruction.mdAdded+22
tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/solution/files/answer.jsonAdded+9
tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/solution/solve.shAdded+4
tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/task.tomlAdded+44
tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/tests/expected.jsonAdded+59
tasks/cuad-dd-goldresourcecorp-12-11-2008-ex-10-1-stra-56ce5e27-v3/tests/grade.pyAdded+330