|
| 1 | +import re |
| 2 | +from io import BytesIO |
| 3 | +from pathlib import Path |
| 4 | +from typing import Any |
| 5 | + |
| 6 | +from inspect_ai import Task, task |
| 7 | +from inspect_ai.dataset import Sample, hf_dataset |
| 8 | +from inspect_ai.model import ChatMessage, ChatMessageUser, ContentImage, ContentText |
| 9 | +from inspect_ai.scorer import ( |
| 10 | + INCORRECT, |
| 11 | + AnswerPattern, |
| 12 | + Score, |
| 13 | + Scorer, |
| 14 | + Target, |
| 15 | + accuracy, |
| 16 | + scorer, |
| 17 | + stderr, |
| 18 | +) |
| 19 | +from inspect_ai.solver import ( |
| 20 | + Generate, |
| 21 | + Solver, |
| 22 | + TaskState, |
| 23 | + solver, |
| 24 | +) |
| 25 | +from PIL import Image |
| 26 | +from platformdirs import user_cache_dir |
| 27 | + |
| 28 | +FREEFORM_TEMPLATE = r""" |
| 29 | +Answer the following question. The entire content of your response should be of the following format: 'ANSWER: $ANSWER' (without quotes) where $ANSWER is your answer. |
| 30 | +
|
| 31 | +{question} |
| 32 | +""" |
| 33 | + |
| 34 | +IMAGE_BASE_DIR = Path(user_cache_dir("inspect_evals")) / "docvqa_images" |
| 35 | + |
| 36 | + |
| 37 | +def _levenshtein_distance(str1: str, str2: str) -> int: |
| 38 | + """Computes a Levenshtein distance, same as Levenshtein.distance in the python-Levenshtein package.""" |
| 39 | + # Create a matrix of size (len(str1) + 1) x (len(str2) + 1) |
| 40 | + matrix = [[0 for j in range(len(str2) + 1)] for i in range(len(str1) + 1)] |
| 41 | + |
| 42 | + # Initialize the first row and column |
| 43 | + for i in range(len(str1) + 1): |
| 44 | + matrix[i][0] = i |
| 45 | + for j in range(len(str2) + 1): |
| 46 | + matrix[0][j] = j |
| 47 | + |
| 48 | + # Fill in the rest of the matrix |
| 49 | + for i in range(1, len(str1) + 1): |
| 50 | + for j in range(1, len(str2) + 1): |
| 51 | + matrix[i][j] = min( |
| 52 | + matrix[i - 1][j] + 1, # deletion |
| 53 | + matrix[i][j - 1] + 1, # insertion |
| 54 | + matrix[i - 1][j - 1] + int(str1[i - 1] != str2[j - 1]), # substitution |
| 55 | + ) |
| 56 | + |
| 57 | + return matrix[len(str1)][len(str2)] |
| 58 | + |
| 59 | + |
| 60 | +def _best_normalized_levenshtein_similiarity( |
| 61 | + completion: str, ground_truths: list[str], threshold: float |
| 62 | +) -> float: |
| 63 | + """ |
| 64 | + Compute a best normalized Levenshtein similiarity, an input into the Average Normalized Levenshtein Similiarity (ANLS) |
| 65 | +
|
| 66 | + The Average Normalized Levenshtein Similarity (ANLS) is defined in equation (1) of |
| 67 | + https://arxiv.org/pdf/1907.00490.pdf |
| 68 | +
|
| 69 | + Note that the "average" is computed by the accuracy metric -- not here. This function computes |
| 70 | + the term inside the summation of equation (1). |
| 71 | + """ |
| 72 | + best_score = 0.0 |
| 73 | + for ground_truth in ground_truths: |
| 74 | + if len(ground_truth) == 0 and len(completion) == 0: |
| 75 | + best_score = 1 |
| 76 | + break |
| 77 | + levenshtein_distance = _levenshtein_distance( |
| 78 | + completion.lower(), ground_truth.lower() |
| 79 | + ) |
| 80 | + normed_levenshtein_distance = levenshtein_distance / max( |
| 81 | + len(completion), len(ground_truth) |
| 82 | + ) |
| 83 | + if normed_levenshtein_distance < threshold: |
| 84 | + score = 1.0 - normed_levenshtein_distance |
| 85 | + else: |
| 86 | + score = 0.0 |
| 87 | + if score > best_score: |
| 88 | + best_score = score |
| 89 | + return best_score |
| 90 | + |
| 91 | + |
| 92 | +@task |
| 93 | +def docvqa() -> Task: |
| 94 | + dataset = hf_dataset( |
| 95 | + path="lmms-lab/DocVQA", |
| 96 | + name="DocVQA", |
| 97 | + split="validation", # "answers" in the "test" split are held back by the authors |
| 98 | + sample_fields=record_to_sample, |
| 99 | + trust=True, |
| 100 | + shuffle=True, |
| 101 | + ) |
| 102 | + |
| 103 | + return Task( |
| 104 | + dataset=dataset, |
| 105 | + solver=[docvqa_solver()], |
| 106 | + scorer=docvqa_scorer(), |
| 107 | + ) |
| 108 | + |
| 109 | + |
| 110 | +@scorer(metrics=[accuracy(), stderr()]) |
| 111 | +def docvqa_scorer() -> Scorer: |
| 112 | + async def normalized_levenshtein_similiarity_score( |
| 113 | + state: TaskState, target: Target |
| 114 | + ) -> Score: |
| 115 | + threshold = 0.5 |
| 116 | + ground_truths = target.target |
| 117 | + match = re.search( |
| 118 | + AnswerPattern.LINE, |
| 119 | + state.output.completion, |
| 120 | + re.IGNORECASE, |
| 121 | + ) |
| 122 | + if match: |
| 123 | + completion = match.groups()[0] |
| 124 | + return Score( |
| 125 | + value=_best_normalized_levenshtein_similiarity( |
| 126 | + completion, ground_truths, threshold |
| 127 | + ), |
| 128 | + answer=completion, |
| 129 | + ) |
| 130 | + |
| 131 | + else: |
| 132 | + # didn't find the scoring pattern |
| 133 | + return Score( |
| 134 | + value=INCORRECT, |
| 135 | + explanation="Scoring pattern not matched in output: " |
| 136 | + + f"{state.output.completion}", |
| 137 | + ) |
| 138 | + |
| 139 | + return normalized_levenshtein_similiarity_score |
| 140 | + |
| 141 | + |
| 142 | +@solver |
| 143 | +def docvqa_solver() -> Solver: |
| 144 | + async def solve(state: TaskState, generate: Generate) -> TaskState: |
| 145 | + state.user_prompt.text = FREEFORM_TEMPLATE.format( |
| 146 | + question=state.user_prompt.text |
| 147 | + ) |
| 148 | + return await generate(state) |
| 149 | + |
| 150 | + return solve |
| 151 | + |
| 152 | + |
| 153 | +def record_to_sample(record: dict[str, Any]) -> Sample: |
| 154 | + # extract image |
| 155 | + image_path = Path(IMAGE_BASE_DIR / record["image"]["path"]) |
| 156 | + |
| 157 | + image_bytes = record["image"]["bytes"] |
| 158 | + assert is_image_png(image_bytes) |
| 159 | + |
| 160 | + if not image_path.exists(): |
| 161 | + print(f"Extracting {image_path.name}") |
| 162 | + # ensure parent |
| 163 | + image_path.parent.mkdir(exist_ok=True, parents=True) |
| 164 | + # reduce the image size |
| 165 | + img = Image.open(BytesIO(image_bytes)) |
| 166 | + img.thumbnail((1024, 1024)) |
| 167 | + # save preserving format |
| 168 | + img.save(image_path, format=img.format) |
| 169 | + |
| 170 | + message: list[ChatMessage] = [ |
| 171 | + ChatMessageUser( |
| 172 | + content=[ |
| 173 | + ContentText(text=record["question"]), |
| 174 | + ContentImage(image=image_path.as_posix()), |
| 175 | + ] |
| 176 | + ) |
| 177 | + ] |
| 178 | + |
| 179 | + return Sample( |
| 180 | + input=message, |
| 181 | + target=record["answers"], |
| 182 | + id=record["questionId"], |
| 183 | + metadata={"document_id": record["docId"]}, |
| 184 | + ) |
| 185 | + |
| 186 | + |
| 187 | +def is_image_png(image_bytes: bytes) -> bool: |
| 188 | + return image_bytes[:8] == b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a" |
0 commit comments