Robust query loading that handles malformed JSON escape sequences. Fallback for when beir.load_queries fails due to JSON parsing errors.
(dataset: str, save_dir: str)
| 126 | |
| 127 | |
| 128 | def load_queries_robust(dataset: str, save_dir: str) -> dict: |
| 129 | """ |
| 130 | Robust query loading that handles malformed JSON escape sequences. |
| 131 | Fallback for when beir.load_queries fails due to JSON parsing errors. |
| 132 | """ |
| 133 | import json |
| 134 | from pathlib import Path |
| 135 | |
| 136 | queries_file = Path(save_dir) / dataset / "queries.jsonl" |
| 137 | if not queries_file.exists(): |
| 138 | raise FileNotFoundError(f"Queries file not found: {queries_file}") |
| 139 | |
| 140 | queries = {} |
| 141 | skipped_lines = 0 |
| 142 | |
| 143 | with open(queries_file, "r", encoding="utf-8") as f: |
| 144 | for line_num, line in enumerate(f, 1): |
| 145 | line = line.strip() |
| 146 | if not line: |
| 147 | continue |
| 148 | |
| 149 | try: |
| 150 | # Try standard JSON parsing first |
| 151 | query_data = json.loads(line) |
| 152 | query_id = query_data.get("_id", str(line_num)) |
| 153 | |
| 154 | # Extract text, handling different possible field names |
| 155 | text = ( |
| 156 | query_data.get("text") |
| 157 | or query_data.get("query") |
| 158 | or query_data.get("body", "") |
| 159 | ) |
| 160 | |
| 161 | queries[query_id] = {"text": text} |
| 162 | |
| 163 | except json.JSONDecodeError: |
| 164 | # Handle malformed escape sequences |
| 165 | try: |
| 166 | # Fix common escape sequence issues |
| 167 | fixed_line = line |
| 168 | # Replace problematic \x sequences with unicode equivalents |
| 169 | import re |
| 170 | |
| 171 | # Replace \xef with proper unicode |
| 172 | fixed_line = re.sub( |
| 173 | r"\\x([0-9a-fA-F]{2})", |
| 174 | lambda m: chr(int(m.group(1), 16)), |
| 175 | fixed_line, |
| 176 | ) |
| 177 | |
| 178 | query_data = json.loads(fixed_line) |
| 179 | query_id = query_data.get("_id", str(line_num)) |
| 180 | |
| 181 | text = ( |
| 182 | query_data.get("text") |
| 183 | or query_data.get("query") |
| 184 | or query_data.get("body", "") |
| 185 | ) |