Download CODE/evaluation/evaluate.py from QLU-LLM/CAD: direct link, hf CLI and curl.
- Browser
- Download file 7.55 kB
-
https://huggingface.co/datasets/QLU-LLM/CAD/resolve/main/CODE/evaluation/evaluate.py
- Command line
-
hf download hf://datasets/QLU-LLM/CAD/CODE/evaluation/evaluate.py
-
curl -L -o evaluate.py https://huggingface.co/datasets/QLU-LLM/CAD/resolve/main/CODE/evaluation/evaluate.py
7.55 kB
| #!/usr/bin/env python3 | |
| """Portable, full-GT CODE evaluation of already-generated DXF artifacts. | |
| This wrapper never executes candidate Python or calls a model/API. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import copy | |
| import csv | |
| import gzip | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import re | |
| import sys | |
| from eval import eval_geometric051 as scope | |
| from eval import eval_geometric052_rc5k_final as metric | |
| from eval import v51_sidecar | |
| import ezdxf | |
| from reporting import aggregate, make_record | |
| HERE = Path(__file__).resolve().parent | |
| MODEL_FAILURES = {'empty', 'syntax_error', 'execution_error', 'length_zero', | |
| 'safety_error', 'resource_error', 'missing_dxf', 'invalid_dxf', | |
| 'generation_failed'} | |
| def sha(path): | |
| return hashlib.sha256(path.read_bytes()).hexdigest() | |
| def json_write(path, value): | |
| with path.open('x', encoding='utf-8') as handle: | |
| json.dump(value, handle, ensure_ascii=False, indent=2, allow_nan=False) | |
| handle.write('\n') | |
| def load_population(name, ids_file=None): | |
| config = json.loads((HERE / 'data/populations.json').read_text())[name] | |
| archive = HERE / 'data' / config['sidecars'] | |
| body = gzip.decompress(archive.read_bytes()) | |
| provenance = json.loads((HERE / 'PROVENANCE.json').read_text()) | |
| assert hashlib.sha256(body).hexdigest() == provenance['sidecars_original_sha256'][archive.name] | |
| records = {} | |
| for line_number, line in enumerate(body.decode('utf-8').splitlines(), 1): | |
| if not line.strip(): | |
| continue | |
| record = v51_sidecar._validate_loaded_row(json.loads(line), archive, line_number) | |
| assert re.fullmatch(r'\d{4}_\d{8}', record['id']) | |
| assert record['id'] not in records | |
| records[record['id']] = record | |
| ids = list(config['ids']) | |
| assert len(ids) == len(set(ids)) and set(ids) <= set(records) | |
| if ids_file: | |
| requested = [line.strip() for line in Path(ids_file).read_text().splitlines() if line.strip()] | |
| if not requested or len(requested) != len(set(requested)) or not set(requested) <= set(ids): | |
| raise ValueError('--ids-file must contain distinct IDs from the named population') | |
| ids = requested | |
| expected = config.get('expected_camr_denominator') | |
| if expected is not None and not ids_file: | |
| assert sum(bool(scope._scope_contracts(records[sid])['full_gt']['annotation_eligible']) for sid in ids) == expected | |
| return ids, records | |
| def load_failures(path, selected): | |
| if not path: | |
| return {} | |
| result = {} | |
| for line in Path(path).read_text(encoding='utf-8').splitlines(): | |
| if not line.strip(): | |
| continue | |
| row = json.loads(line) | |
| sid, status = str(row['id']), str(row['status']) | |
| if sid in result: | |
| raise ValueError('Duplicate ID in failure manifest: ' + sid) | |
| if status not in MODEL_FAILURES | {'scored'}: | |
| raise ValueError('Unrecognized/infrastructure/API-unavailable status must not be silently zero-filled: ' + status) | |
| if sid in selected: | |
| result[sid] = status | |
| return result | |
| def run(args): | |
| ids, sidecars = load_population(args.population, args.ids_file) | |
| gt_dir = args.gt_dir.resolve() if args.gt_dir else args.dataset_root.resolve() / 'reference_dxf' | |
| if not args.pred_dir.is_dir(): | |
| raise ValueError('--pred-dir must be an existing directory (it may be empty)') | |
| failures = load_failures(args.failure_manifest, set(ids)) | |
| # Missing or modified references are infrastructure errors, not model zeros. | |
| for sid in ids: | |
| gt = gt_dir / (sid + '.dxf') | |
| if not gt.is_file() or sha(gt) != sidecars[sid]['gt_dxf_sha256']: | |
| raise ValueError('Missing or mismatched reference DXF: ' + sid) | |
| if args.output.exists(): | |
| raise FileExistsError('Refusing to overwrite existing output directory: ' + str(args.output)) | |
| args.output.mkdir(parents=True) | |
| (args.output / 'raw').mkdir() | |
| items = [] | |
| for index, sid in enumerate(ids, 1): | |
| original = sidecars[sid] | |
| contract = scope._scope_contracts(original) | |
| gt = gt_dir / (sid + '.dxf') | |
| pred = args.pred_dir / (sid + '.dxf') | |
| status = failures.get(sid) | |
| if status in MODEL_FAILURES: | |
| row = make_record(sid, contract, status=status) | |
| elif not pred.is_file(): | |
| if status == 'scored': | |
| raise ValueError('Manifest says scored but DXF is missing: ' + sid) | |
| row = make_record(sid, contract, status='missing_dxf') | |
| else: | |
| # A supplied artifact must be readable DXF, not merely have the extension. | |
| try: | |
| ezdxf.readfile(pred) | |
| except (ezdxf.DXFError, UnicodeError) as error: | |
| row = make_record(sid, contract, status='invalid_dxf', error=type(error).__name__) | |
| else: | |
| before = sha(pred) | |
| sidecar = copy.deepcopy(original) | |
| sidecar['gt_dxf'] = str(gt) | |
| result = metric.score_dxf_pair(pred, gt, sidecar=sidecar, category=sidecar['category']) | |
| # Unexpected scoring/infrastructure errors propagate; they are not model failures. | |
| assert sha(pred) == before, 'Candidate changed during scoring: ' + sid | |
| row = make_record(sid, contract, result=result) | |
| raw_path = args.output / 'raw' / (sid + '.json') | |
| json_write(raw_path, result) | |
| row.update(raw_result='raw/' + sid + '.json', raw_result_sha256=sha(raw_path), predicted_dxf_sha256=before) | |
| items.append(row) | |
| if index % 50 == 0 or index == len(ids): | |
| print(json.dumps({'progress': index, 'total': len(ids)}), flush=True) | |
| with (args.output / 'per_item.jsonl').open('x', encoding='utf-8') as handle: | |
| for row in items: | |
| handle.write(json.dumps(row, ensure_ascii=False, allow_nan=False) + '\n') | |
| summary = aggregate(items) | |
| summary.update(metric_version=metric.METRIC_VERSION, population=args.population, | |
| custom_subset=bool(args.ids_file), input_mode='pre-generated DXF artifacts', | |
| candidate_programs_executed=False, selected_ids=ids) | |
| json_write(args.output / 'summary.json', summary) | |
| with (args.output / 'summary.csv').open('x', encoding='utf-8', newline='') as handle: | |
| writer = csv.DictWriter(handle, fieldnames=list(summary['metrics'])) | |
| writer.writeheader() | |
| writer.writerow(summary['metrics']) | |
| print(json.dumps({k: v for k, v in summary.items() if k != 'selected_ids'}, indent=2)) | |
| return summary | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('--pred-dir', type=Path, required=True, help='DXFs named <sample_id>.dxf') | |
| parser.add_argument('--dataset-root', type=Path, default=HERE.parent, help='CODE directory after reference_dxf.zip extraction') | |
| parser.add_argument('--gt-dir', type=Path, help='Optional reference_dxf directory override') | |
| parser.add_argument('--population', choices=['test1045', 'paper1041', 'validation254'], default='test1045') | |
| parser.add_argument('--ids-file', type=Path, help='Optional explicit subset; summary is marked custom_subset') | |
| parser.add_argument('--failure-manifest', type=Path, help='Optional JSONL with id/status execution outcomes') | |
| parser.add_argument('--output', type=Path, required=True, help='A new output directory') | |
| return run(parser.parse_args()) | |
| if __name__ == '__main__': | |
| main() | |