Datasets:
Formats:
json
Languages:
English
Size:
< 1K
Tags:
vision-language
metaphor
figurative-language
multimodal-benchmark
modality-gap
lexicalized-metaphor
License:
File size: 6,932 Bytes
a98f59b | 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 | #!/usr/bin/env python3
import argparse
import json
import re
import shutil
from pathlib import Path
OPTION_PREFIX_RE = re.compile(r"^\s*[A-Ea-e]\s*[\)\.\:\-]\s*")
def clean_option(text: str) -> str:
"""Remove leading A), B), etc. and normalize whitespace."""
text = OPTION_PREFIX_RE.sub("", str(text)).strip()
return " ".join(text.split())
def normalize_text(text: str) -> str:
return " ".join(str(text).strip().split())
def make_new_id(i: int) -> str:
return f"metalex_{i:06d}"
def load_jsonl(path: Path):
rows = []
with path.open("r", encoding="utf-8") as f:
for line_no, line in enumerate(f, start=1):
if line.strip():
try:
rows.append(json.loads(line))
except json.JSONDecodeError as e:
raise ValueError(f"Bad JSON on line {line_no}: {e}") from e
return rows
def write_jsonl(path: Path, rows):
with path.open("w", encoding="utf-8") as f:
for row in rows:
f.write(json.dumps(row, ensure_ascii=False) + "\n")
def normalize_dataset(
input_jsonl: Path,
input_images_dir: Path,
output_dir: Path,
source: str = "English Wiktionary",
split: str = "test",
example_n: int = 25,
copy_images: bool = True,
):
output_data_dir = output_dir / "data"
output_images_dir = output_dir / "images"
output_examples_dir = output_dir / "examples"
output_data_dir.mkdir(parents=True, exist_ok=True)
output_images_dir.mkdir(parents=True, exist_ok=True)
output_examples_dir.mkdir(parents=True, exist_ok=True)
rows = load_jsonl(input_jsonl)
normalized_rows = []
warnings = []
for new_i, entry in enumerate(rows):
old_id = entry.get("id", new_i)
new_id = make_new_id(new_i)
idiom = normalize_text(entry.get("word", entry.get("idiom", "")))
literal_text = normalize_text(entry.get("literal", entry.get("literal_text", "")))
figurative = normalize_text(entry.get("figurative", entry.get("correct_definition", "")))
raw_options = entry.get("options", entry.get("choices", []))
choices = [clean_option(o) for o in raw_options]
# In the original MetaLex files, answer is always option A.
# Therefore, after removing A)/B)/... prefixes, the gold answer is choices[0].
if not choices:
raise ValueError(f"{new_id}: no options found.")
answer_index = 0
answer = choices[0]
# Keep the long definition separately, but do NOT insert it into choices.
# This preserves the exact original MCQ options.
if figurative and figurative.lower() != answer.lower():
warnings.append(
f"{new_id}: figurative field differs from option A; kept option A as the answer."
)
src_image = input_images_dir / f"{old_id}_img.png"
dst_image_name = f"{new_id}.png"
dst_image = output_images_dir / dst_image_name
if src_image.exists():
if copy_images:
shutil.copy2(src_image, dst_image)
else:
shutil.move(src_image, dst_image)
else:
warnings.append(f"{new_id}: missing image {src_image}")
normalized = {
"id": new_id,
"idiom": idiom,
"literal_text": literal_text,
"image": f"images/{dst_image_name}",
"correct_definition": figurative,
"choices": choices,
"answer_index": answer_index,
"answer": answer,
"split": split,
"source": source,
}
for optional_key in [
"category",
"source_domain",
"target_domain",
"notes",
"license",
"wiktionary_url",
]:
if optional_key in entry and entry[optional_key] not in ("", None):
normalized[optional_key] = entry[optional_key]
normalized_rows.append(normalized)
main_jsonl = output_data_dir / "metalex_test.jsonl"
examples_jsonl = output_examples_dir / "metalex_examples.jsonl"
write_jsonl(main_jsonl, normalized_rows)
write_jsonl(examples_jsonl, normalized_rows[:example_n])
schema = {
"id": "stable string id, e.g. metalex_000001",
"idiom": "lexicalised metaphor string",
"literal_text": "literal paraphrase used to generate/evaluate the scene",
"image": "relative path to literal image",
"correct_definition": "full gold figurative meaning/definition",
"choices": "multiple-choice answer options without A/B/C prefixes",
"answer_index": "always 0 because the correct answer is always option A in the source file",
"answer": "choices[0], the correct option text",
"split": "dataset split",
"source": "source lexicon or source description",
}
with (output_dir / "schema.json").open("w", encoding="utf-8") as f:
json.dump(schema, f, ensure_ascii=False, indent=2)
if warnings:
warning_path = output_dir / "normalization_warnings.txt"
warning_path.write_text("\n".join(warnings) + "\n", encoding="utf-8")
print(f"Wrote {len(warnings)} warnings to {warning_path}")
print(f"Wrote {len(normalized_rows)} rows to {main_jsonl}")
print(f"Wrote {min(example_n, len(normalized_rows))} examples to {examples_jsonl}")
print(f"Images written to {output_images_dir}")
def main():
parser = argparse.ArgumentParser(description="Normalize MetaLex JSONL and image filenames for upload.")
parser.add_argument(
"--base_dir",
type=Path,
default=Path(r"c:\Users\pranjal\Desktop\ProjectVLM\dataset_to_upload"),
help="Folder containing met_schema.json and images/",
)
parser.add_argument("--json_name", default="met_schema.json", help="Input JSONL filename.")
parser.add_argument("--images_name", default="images", help="Input image folder name.")
parser.add_argument("--out_dir", type=Path, default=None, help="Output folder. Default: base_dir/metalex_hf_upload")
parser.add_argument("--source", default="English Wiktionary")
parser.add_argument("--split", default="test")
parser.add_argument("--example_n", type=int, default=25)
parser.add_argument("--move_images", action="store_true", help="Move images instead of copying them.")
args = parser.parse_args()
base_dir = args.base_dir
input_jsonl = base_dir / args.json_name
input_images_dir = base_dir / args.images_name
output_dir = args.out_dir or (base_dir / "metalex_hf_upload")
normalize_dataset(
input_jsonl=input_jsonl,
input_images_dir=input_images_dir,
output_dir=output_dir,
source=args.source,
split=args.split,
example_n=args.example_n,
copy_images=not args.move_images,
)
if __name__ == "__main__":
main()
|