metalex / normalize.py
metalex001's picture
Upload 507 files
a98f59b verified
#!/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()