"""Candidate routing, validation calibration and benchmark scoring.""" import contextlib import hashlib import io import json import math from pathlib import Path import re from vendor.metrics.bleu.bleu import Bleu from vendor.metrics.cider.cider import Cider from vendor.metrics.rouge.rouge import Rouge ROOT = Path(__file__).resolve().parent DATASETS = ('levir', 'whu', 'dubai') BETAS = [round(step * .02, 2) for step in range(11)] def read(path): with Path(path).open(encoding='utf-8') as handle: return json.load(handle) def write(path, value): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_suffix('.tmp') temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + '\n', encoding='utf-8') temporary.replace(path) def read_rows(path): with Path(path).open(encoding='utf-8') as handle: return [json.loads(line) for line in handle if line.strip()] def digest(path): fingerprint = hashlib.sha256() with Path(path).open('rb') as handle: while chunk := handle.read(1024 * 1024): fingerprint.update(chunk) return fingerprint.hexdigest() def corpus(dataset, split): return read(ROOT / 'data' / dataset / f'{split}.json') def profile(dataset): return read(ROOT / 'data' / dataset / 'config.json') def unchanged(dataset, text, templates): if dataset != 'dubai': return text in templates normalized = ' '.join(re.findall(r'[a-z0-9]+', text.lower())) marker = re.search(r'\b(?:no changes?(?:\s|$)|no changed? to mention|no difference|unchanged|nothing(?: has)? changed|(?:remain(?:s|ed)?|appears?|is|was) the same|the same$)\b', normalized) event = re.search(r'\b(?:built|builds?|construct(?:ed|s|ing)?|new|add(?:ed|s|ing)?|creat(?:ed|es|ing)|realiz(?:ed|es)|edifi(?:ed|es)|demolish(?:ed|es)?|remov(?:ed|es|ing)|urbaniz(?:ed|es|ation)|extend(?:ed|s)?|enlarg(?:ed|es)|expand(?:ed|s|ing)?|increas(?:ed|es)|decreas(?:ed|es)|disappear(?:ed|s|ing)?|different|bigger|smaller)\b', normalized) return normalized in templates or (bool(marker) and not event) def next_stage(dataset, captions, anchor, templates): if not unchanged(dataset, captions[anchor], templates): return anchor, True if dataset == 'dubai': anchor = next(index for index, text in enumerate(captions) if unchanged(dataset, text, templates)) return anchor, False def decision(dataset, row, beta, templates): captions = row['captions'] anchor = max(row['stage1'], key=lambda item: item[1])[0] locked, routed = next_stage(dataset, captions, anchor, templates) ranked = row.get('stage2', []) if not routed or not ranked: return locked return max(ranked, key=lambda item: math.log(max(item[1], 1e-30)) - beta * len(captions[item[0]].split()))[0] def metrics(dataset, references, captions, full=False): vocab = read(ROOT / 'data' / dataset / 'vocab.json') if dataset == 'levir' else None def encode(text): return ' '.join(str(vocab.get(word, 1)) for word in text.split()) if vocab is not None else text refs = [[encode(' '.join(tokens)) for tokens in row['references']] for row in references] hyps = [[encode(text)] for text in captions] with contextlib.redirect_stdout(io.StringIO()): bleu, _ = Bleu(4).compute_score(refs, hyps) cider, _ = Cider().compute_score(refs, hyps) values = {f'BLEU{index}': float(value * 100) for index, value in enumerate(bleu, 1)} values['CIDEr'] = float(cider * 100) if full: import os import shutil import tempfile from vendor.metrics.meteor import meteor if shutil.which('java') is None: raise RuntimeError('METEOR 1.5 requires Java on PATH.') source = Path(meteor.__file__).parent directory = Path(os.environ.get('METEOR_TEMP', tempfile.gettempdir())) / 'ctr-meteor-1.5' if not str(directory).isascii(): raise RuntimeError('Set METEOR_TEMP to a writable ASCII-only directory.') for path in ('meteor-1.5.jar', 'data/paraphrase-en.gz'): target = directory / path target.parent.mkdir(parents=True, exist_ok=True) if not target.is_file() or target.stat().st_size != (source / path).stat().st_size: shutil.copyfile(source / path, target) original = meteor.__file__ try: meteor.__file__ = str(directory / 'meteor.py') values['METEOR'] = float(meteor.Meteor().compute_score(refs, hyps)[0] * 100) finally: meteor.__file__ = original values['ROUGE_L'] = float(Rouge().compute_score(refs, hyps)[0] * 100) values['S_m_star'] = sum(values[key] for key in ('BLEU4', 'METEOR', 'ROUGE_L', 'CIDEr')) / 4 return values def evaluate(dataset, split, rows, beta, full=False, stage1_only=False): references = corpus(dataset, split) if [row['name'] for row in references] != [row['name'] for row in rows]: raise ValueError(f'{dataset}/{split}: candidate names do not match the benchmark ordering') templates = profile(dataset)['templates'] if stage1_only: selected = [max(row['stage1'], key=lambda item: item[1])[0] for row in rows] else: selected = [decision(dataset, row, beta, templates) for row in rows] outputs = [row['captions'][index] for row, index in zip(rows, selected, strict=True)] return metrics(dataset, references, outputs, full), outputs def select_beta(dataset, rows): curve = [{'beta': beta, 'metrics': evaluate(dataset, 'val', rows, beta)[0]} for beta in BETAS] def compare(entry): values = entry['metrics'] return values['CIDEr'] + 2 * values['BLEU4'], values['CIDEr'], values['BLEU4'], -entry['beta'] return max(curve, key=compare), curve