File size: 8,948 Bytes
2c76448 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 | """Score one generation task: Content Faithfulness (CF), Instruction Following (IF), Aesthetic Quality (AQ).
Run `run_ocr.py` first. Predictions are read from <pred_dir>/<task>/<id>.png.
python eval/score_generation.py --task multi_image --pred_dir outputs/my_model --workers 16
CF text: GPT-4.1 extracts the slide text the instruction requires; OCR lines
are re-joined against those strings; each required string is matched
to its closest OCR line by Levenshtein distance;
S_text = max(10 - 9 * sum(dist) / sum(len), 1).
multi_image adds an input-image preservation score (judge `overall_score`)
and CF = (S_text + S_image) / 2.
IF unweighted mean of six sub-dimensions (text or style_json prompt;
template cases also show the reference slide).
AQ unweighted mean of four sub-dimensions, judged from the output image only.
"""
import argparse
import json
import os
import re
from concurrent.futures import ThreadPoolExecutor
from itertools import combinations
from pathlib import Path
from rapidfuzz import fuzz
from common import (bench_path, chat, get_client, image_part, load_jsonl, load_prompt, mean,
subdimension_mean, text_part, write_jsonl)
EXTRACT_PROMPT = (
"From the following PPT instruction, extract ALL text strings that are explicitly written out and are required "
"to appear on the PPT page. This includes any quoted text, statements, captions, labels, or any other text that "
"is directly specified in the instruction as content to be displayed on the slide. DO NOT infer or generate new "
"text. Only extract what is explicitly present in the instruction and is required to be shown on the PPT. "
"Return ONLY a JSON array (Python list) of strings, each string is a text to be displayed. Do not output "
"anything except the JSON array."
)
# ----------------------------------------------------------------- CF (text)
def levenshtein(a, b):
if a == b:
return 0
if not a or not b:
return len(a) or len(b)
prev = list(range(len(b) + 1))
for i, ca in enumerate(a, 1):
cur = [i]
for j, cb in enumerate(b, 1):
cur.append(min(cur[j - 1] + 1, prev[j] + 1, prev[j - 1] + (ca != cb)))
prev = cur
return prev[-1]
def _norm(s):
return "".join(s.lower().split())
def rejoin_lines(lines, targets, max_extra=3):
"""Join OCR lines that together spell a required string (RapidFuzz ratio > 90)."""
target_norms = [_norm(t) for t in targets]
out, used = [], set()
for i, line in enumerate(lines):
if i in used:
continue
cur = _norm(line)
if cur in target_norms:
out.append(line)
used.add(i)
continue
joined = None
for tn in target_norms:
if fuzz.ratio(cur, tn[: len(cur)]) <= 90:
continue
for r in range(1, max_extra + 1):
for combo in combinations(range(i + 1, len(lines)), r):
cand = " ".join(lines[k] for k in (i,) + combo)
if fuzz.ratio(_norm(cand), tn) > 90:
joined = (cand, (i,) + combo)
break
if joined:
break
if joined:
break
if joined:
out.append(joined[0])
used.update(joined[1])
else:
out.append(line)
used.add(i)
return out
def text_score(targets, ocr_lines):
dist = sum(min(levenshtein(t, g) for g in ocr_lines) for t in targets)
total = sum(len(t) for t in targets)
return round(max(10 - 9 * dist / total, 1), 2)
def extract_style_json(instruction):
"""Return the JSON block of a style_json instruction (text after '### SLIDE JSON:')."""
idx = instruction.find("### SLIDE JSON:")
if idx < 0:
idx = instruction.find("```json")
if idx < 0:
return instruction
rest = instruction[idx:]
m = re.search(r"```json\s*\n(.*?)```", rest, re.DOTALL)
if m:
return m.group(1).strip()
s, e = rest.find("{"), rest.rfind("}")
return rest[s : e + 1] if 0 <= s < e else rest
# ------------------------------------------------------------------- scoring
def score_cf(client, task, case, img, ocr_file):
targets = chat(client, EXTRACT_PROMPT, case["instruction"], temperature=0.2, max_tokens=800)
targets = [str(t).strip() for t in targets if str(t).strip()] if isinstance(targets, list) else []
lines = [l.strip() for l in open(ocr_file, encoding="utf-8")] if os.path.exists(ocr_file) else []
lines = [l for l in lines if l]
if not targets or not lines:
return {"cf_error": "no required text extracted" if not targets else "no OCR text"}
out = {"cf_text": text_score(targets, rejoin_lines(lines, targets))}
out["cf"] = out["cf_text"]
if task == "multi_image":
content = [text_part("Generated PPT:"), image_part(img), text_part("Sub-Image List (required sub-images):")]
for k, p in enumerate(case["input_images"], 1):
content += [text_part(f"Sub-Image {k}:"), image_part(bench_path(p))]
res = chat(client, load_prompt("content_faithfulness.txt"), content, temperature=0.2, max_tokens=1200)
out["cf_image"] = float(res["overall_score"])
out["cf"] = round((out["cf_text"] + out["cf_image"]) / 2, 2)
return out
def score_if(client, task, case, img):
is_json = "JSON" in case["instruction"]
if is_json:
content = [text_part(f"## Style JSON Specification\n\n```json\n{extract_style_json(case['instruction'])}\n```\n\n")]
else:
content = [text_part(f"## Style Description\n\n{case['instruction']}\n\n")]
if task == "template":
content += [
text_part(
"## Reference Slide Image (for style only)\n\nThe following image is a reference slide from the same "
"presentation. Use it only to infer the visual style (palette, typography, background, decorative "
"motifs, etc.), not for layout or content placement.\n"
),
image_part(bench_path(case["input_images"][0])),
]
content += [
text_part("## Generated Slide Image\n\nThe image below is the AI-generated slide. Evaluate how well it follows the style instructions above."),
image_part(img),
]
prompt = "style_instruction_following_json.txt" if is_json else "style_instruction_following_text.txt"
return {"if": subdimension_mean(chat(client, load_prompt(prompt), content, temperature=0.2, max_tokens=2000))}
def score_aq(client, img):
content = [text_part("## Generated Slide Image\n\nThe image below is the AI-generated slide. Evaluate its aesthetic quality."), image_part(img)]
return {"aq": subdimension_mean(chat(client, load_prompt("aesthetic_quality.txt"), content, temperature=0.2, max_tokens=2000))}
def score_case(client, task, case, img, ocr_file):
"""Each metric is scored independently; a failure leaves only that metric empty."""
out = {"id": case["id"], "source": case["source"], "prompt_type": case["prompt_type"]}
for name, fn in (("cf", lambda: score_cf(client, task, case, img, ocr_file)),
("if", lambda: score_if(client, task, case, img)),
("aq", lambda: score_aq(client, img))):
try:
out.update(fn())
except Exception as e:
out[f"{name}_error"] = repr(e)
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--task", required=True, choices=["t2i", "template", "multi_image"])
ap.add_argument("--pred_dir", required=True)
ap.add_argument("--ocr_dir", default=None, help="Defaults to <pred_dir>/ocr.")
ap.add_argument("--out", default=None, help="Defaults to <pred_dir>/scores/<task>.jsonl.")
ap.add_argument("--workers", type=int, default=8)
args = ap.parse_args()
client = get_client()
ocr_dir = Path(args.ocr_dir or os.path.join(args.pred_dir, "ocr")) / args.task
cases = load_jsonl(bench_path(f"data/{args.task}.jsonl"))
def run(case):
img = Path(args.pred_dir) / args.task / f"{case['id']}.png"
if not img.exists():
return {"id": case["id"], "error": "missing prediction"}
return score_case(client, args.task, case, str(img), str(ocr_dir / f"{case['id']}.txt"))
with ThreadPoolExecutor(args.workers) as ex:
rows = list(ex.map(run, cases))
out = args.out or os.path.join(args.pred_dir, "scores", f"{args.task}.jsonl")
write_jsonl(out, rows)
summary = {m: mean(r[m] for r in rows if r.get(m) is not None) for m in ("cf", "if", "aq")}
summary["n_scored"] = {m: sum(r.get(m) is not None for r in rows) for m in ("cf", "if", "aq")}
print(json.dumps({"task": args.task, **summary}, indent=1))
if __name__ == "__main__":
main()
|