VictorLJZ commited on
Commit
eaff77c
·
1 Parent(s): ab428dd

refactored rexvqa benchmark

Browse files
benchmarking/benchmarks/rexvqa_benchmark.py CHANGED
@@ -2,10 +2,12 @@
2
 
3
  import json
4
  import os
5
- from typing import Dict, List, Optional, Any
6
  from datasets import load_dataset
7
  from .base import Benchmark, BenchmarkDataPoint
8
  from pathlib import Path
 
 
9
 
10
 
11
  class ReXVQABenchmark(Benchmark):
@@ -47,11 +49,128 @@ class ReXVQABenchmark(Benchmark):
47
 
48
  super().__init__(data_dir, **kwargs)
49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  def _load_data(self) -> None:
51
  """Load ReXVQA data from local JSON file."""
52
  try:
 
 
 
 
53
  # Construct path to the JSON file
54
- json_file_path = os.path.join("benchmarking", "data", "rexvqa", "test_vqa_data.json")
55
 
56
  # Check if file exists
57
  if not os.path.exists(json_file_path):
 
2
 
3
  import json
4
  import os
5
+ from typing import Dict, Optional, Any
6
  from datasets import load_dataset
7
  from .base import Benchmark, BenchmarkDataPoint
8
  from pathlib import Path
9
+ import subprocess
10
+ from huggingface_hub import hf_hub_download, list_repo_files
11
 
12
 
13
  class ReXVQABenchmark(Benchmark):
 
49
 
50
  super().__init__(data_dir, **kwargs)
51
 
52
+ @staticmethod
53
+ def download_rexgradient_images(output_dir: str = "benchmarking/data/rexvqa", repo_id: str = "rajpurkarlab/ReXGradient-160K"):
54
+ """Download and extract ReXGradient-160K images if not already present."""
55
+ output_dir = Path(output_dir)
56
+ tar_path = output_dir / "deid_png.tar"
57
+ images_dir = output_dir / "images"
58
+
59
+ # Check if images already exist
60
+ if images_dir.exists() and any(images_dir.rglob("*.png")):
61
+ print(f"Images already exist in {images_dir}, skipping download.")
62
+ return
63
+ output_dir.mkdir(parents=True, exist_ok=True)
64
+ print(f"Output directory: {output_dir}")
65
+ try:
66
+ print("Listing files in repository...")
67
+ files = list_repo_files(repo_id, repo_type='dataset')
68
+ part_files = [f for f in files if f.startswith("deid_png.part")]
69
+ if not part_files:
70
+ print("No part files found. The images might be in a different format.")
71
+ return
72
+ print(f"Found {len(part_files)} part files.")
73
+ # Download part files
74
+ for part_file in part_files:
75
+ output_path = output_dir / part_file
76
+ if output_path.exists():
77
+ print(f"Skipping {part_file} (already exists)")
78
+ continue
79
+ print(f"Downloading {part_file}...")
80
+ hf_hub_download(
81
+ repo_id=repo_id,
82
+ filename=part_file,
83
+ local_dir=output_dir,
84
+ local_dir_use_symlinks=False,
85
+ repo_type='dataset'
86
+ )
87
+ # Concatenate part files
88
+ if not tar_path.exists():
89
+ print("\nConcatenating part files...")
90
+ with open(tar_path, 'wb') as tar_file:
91
+ for part_file in sorted(part_files):
92
+ part_path = output_dir / part_file
93
+ if part_path.exists():
94
+ print(f"Adding {part_file}...")
95
+ with open(part_path, 'rb') as f:
96
+ tar_file.write(f.read())
97
+ else:
98
+ print(f"Warning: {part_file} not found, skipping...")
99
+ else:
100
+ print(f"Tar file already exists: {tar_path}")
101
+ # Extract tar file
102
+ if tar_path.exists():
103
+ print("\nExtracting images...")
104
+ images_dir.mkdir(exist_ok=True)
105
+ if any(images_dir.rglob("*.png")):
106
+ print("Images already extracted.")
107
+ else:
108
+ try:
109
+ subprocess.run([
110
+ "tar", "-xf", str(tar_path),
111
+ "-C", str(images_dir)
112
+ ], check=True)
113
+ print("Extraction completed!")
114
+ except subprocess.CalledProcessError as e:
115
+ print(f"Error extracting tar file: {e}")
116
+ return
117
+ except FileNotFoundError:
118
+ print("Error: 'tar' command not found. Please install tar or extract manually.")
119
+ return
120
+ png_files = list(images_dir.rglob("*.png"))
121
+ print(f"Extracted {len(png_files)} PNG images to {images_dir}")
122
+
123
+ # Clean up part and tar files after successful extraction
124
+ print("Cleaning up part and tar files...")
125
+ # Remove deid_png.part* files
126
+ for part_file in output_dir.glob("deid_png.part*"):
127
+ try:
128
+ part_file.unlink()
129
+ print(f"Deleted {part_file}")
130
+ except Exception as e:
131
+ print(f"Could not delete {part_file}: {e}")
132
+ # Remove deid_png.tar
133
+ if tar_path.exists():
134
+ try:
135
+ tar_path.unlink()
136
+ print(f"Deleted {tar_path}")
137
+ except Exception as e:
138
+ print(f"Could not delete {tar_path}: {e}")
139
+ except Exception as e:
140
+ print(f"Error: {e}")
141
+
142
+ @staticmethod
143
+ def download_test_vqa_data_json(output_dir: str = "benchmarking/data/rexvqa", repo_id: str = "rajpurkarlab/ReXVQA"):
144
+ """Download test_vqa_data.json from the ReXVQA HuggingFace repo if not already present."""
145
+ output_dir = Path(output_dir)
146
+ output_dir.mkdir(parents=True, exist_ok=True)
147
+ json_path = output_dir / "metadata" / "test_vqa_data.json"
148
+ if json_path.exists():
149
+ print(f"test_vqa_data.json already exists at {json_path}, skipping download.")
150
+ return
151
+ print(f"Downloading test_vqa_data.json to {json_path}...")
152
+ try:
153
+ hf_hub_download(
154
+ repo_id=repo_id,
155
+ filename="metadata/test_vqa_data.json",
156
+ local_dir=output_dir,
157
+ local_dir_use_symlinks=False,
158
+ repo_type='dataset'
159
+ )
160
+ print("Download complete.")
161
+ except Exception as e:
162
+ print(f"Error downloading test_vqa_data.json: {e}")
163
+ print("You may need to accept the license agreement on HuggingFace.")
164
+
165
  def _load_data(self) -> None:
166
  """Load ReXVQA data from local JSON file."""
167
  try:
168
+ # Check for images and test_vqa_data.json, download if missing
169
+ self.download_test_vqa_data_json()
170
+ self.download_rexgradient_images()
171
+
172
  # Construct path to the JSON file
173
+ json_file_path = os.path.join("benchmarking", "data", "rexvqa", "metadata", "test_vqa_data.json")
174
 
175
  # Check if file exists
176
  if not os.path.exists(json_file_path):