Spaces:
Sleeping
Sleeping
File size: 15,673 Bytes
90c099b | 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 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 | """
Robust JSON parsing utilities for LLM responses
"""
import json
import re
from typing import Any, Dict, List, Optional
def extract_json_from_text(text: str) -> Optional[str]:
"""
Extract JSON from text by removing markdown code block markers
Args:
text: Text that may contain JSON in markdown code blocks or plain JSON
Returns:
Extracted JSON string or None if not found
"""
if not text:
return None
text_stripped = text.strip()
# Try to parse as plain JSON first (no code blocks)
try:
json.loads(text_stripped)
return text_stripped
except json.JSONDecodeError:
pass
# Remove markdown code block markers: ```json ... ``` or ``` ... ```
if text_stripped.startswith('```json'):
# Remove ```json at start and ``` at end
if text_stripped.endswith('```'):
text_stripped = text_stripped[7:-3].strip()
else:
# No closing ```, just remove opening
text_stripped = text_stripped[7:].strip()
elif text_stripped.startswith('```'):
# Handle ``` ... ``` (without json label)
if text_stripped.endswith('```'):
text_stripped = text_stripped[3:-3].strip()
else:
return None
# Try to parse as JSON after removing code block markers
try:
json.loads(text_stripped)
return text_stripped
except json.JSONDecodeError:
return None
def parse_json_response(text: str, fallback: Any = None) -> Any:
"""
Parse JSON from LLM response with robust error handling
Args:
text: LLM response text
fallback: Fallback value if parsing fails
Returns:
Parsed JSON object or fallback
"""
if not text:
return fallback
# Extract JSON from text
json_str = extract_json_from_text(text)
if json_str is None:
return fallback
try:
return json.loads(json_str)
except json.JSONDecodeError as e:
# Try to fix common JSON issues
json_str = fix_json_common_issues(json_str)
try:
return json.loads(json_str)
except json.JSONDecodeError:
return fallback
def fix_json_common_issues(json_str: str) -> str:
"""
Fix common JSON formatting issues
Args:
json_str: JSON string that may have issues
Returns:
Fixed JSON string
"""
# Remove trailing commas
json_str = re.sub(r',\s*}', '}', json_str)
json_str = re.sub(r',\s*]', ']', json_str)
# Fix single quotes to double quotes (basic)
json_str = re.sub(r"'(\w+)':", r'"\1":', json_str)
# Remove comments (basic)
json_str = re.sub(r'//.*?$', '', json_str, flags=re.MULTILINE)
json_str = re.sub(r'/\*.*?\*/', '', json_str, flags=re.DOTALL)
return json_str
def parse_keywords_json(response: str) -> List[str]:
"""
Parse keywords from JSON response
Expected format:
{"keywords": ["keyword1", "keyword2", ...]}
or
["keyword1", "keyword2", ...]
Args:
response: LLM response text
Returns:
List of keywords, or empty list if parsing fails
"""
if response is None:
return []
parsed = parse_json_response(response, fallback=None)
if parsed is None:
return []
# Handle dict format: {"keywords": [...]}
if isinstance(parsed, dict):
if "keywords" in parsed and isinstance(parsed["keywords"], list):
return parsed["keywords"][:5]
return []
# Handle list format: ["keyword1", "keyword2", ...]
if isinstance(parsed, list):
return parsed[:5]
return []
def parse_summary_json(response: str) -> str:
"""
Parse summary from JSON response
Expected format:
{"summary": "summary text"}
or
{"text": "summary text", "summary": "summary text"}
Args:
response: LLM response text
Returns:
Summary text
"""
parsed = parse_json_response(response, fallback=None)
if parsed is None:
# Fallback to text parsing
return response.strip()
if isinstance(parsed, dict):
# Try different possible keys
for key in ["summary", "text", "content", "description"]:
if key in parsed:
summary = str(parsed[key]).strip()
if summary:
return summary
# Fallback to text parsing
return response.strip()
def parse_review_json(response: str, review_format: str = "detailed") -> Dict[str, Any]:
"""
Parse review from JSON or markdown response
Expected formats:
- JSON: {"summary": "...", "soundness": 5, ...}
- Markdown: ## Summary\n\n...\n## Soundness\n\n...
Args:
response: LLM response text (JSON or markdown)
review_format: Review format type (detailed, summary, structured)
Returns:
Review dictionary with parsed fields
"""
# First try to parse as JSON
parsed = parse_json_response(response, fallback=None)
if parsed is not None and isinstance(parsed, dict):
# JSON format - ensure it has required fields
if "review" not in parsed:
parsed["review"] = response.strip()
return parsed
# If not JSON, try to parse as markdown
if "## " in response or "##" in response:
markdown_parsed = parse_review_markdown(response)
if len(markdown_parsed) > 1: # More than just "review" field
return markdown_parsed
# Fallback to text parsing
return {"review": response.strip()}
def parse_review_markdown(markdown_text: str) -> Dict[str, Any]:
"""
Parse review from markdown format with sections like:
## Summary
...
## Soundness
...
etc.
Args:
markdown_text: Markdown formatted review text
Returns:
Review dictionary with parsed fields
"""
review_dict = {"review": markdown_text.strip()}
# Pattern to match markdown sections: ## SectionName\n\ncontent
section_pattern = r'##\s*([^\n]+)\s*\n\n(.*?)(?=\n##\s*|$)'
matches = re.finditer(section_pattern, markdown_text, re.DOTALL)
for match in matches:
section_name = match.group(1).strip()
section_content = match.group(2).strip()
# Normalize section name (case-insensitive, remove extra spaces)
section_name_lower = section_name.lower()
# Map section names to dictionary keys
if "summary" in section_name_lower:
review_dict["summary"] = section_content
elif "soundness" in section_name_lower:
# Extract score - prioritize single float number (e.g., "3.0", "4.5")
# If format is "3 / 5" or "**3 / 5**", extract the number before the slash
score_val = None
lines = section_content.split('\n')
if lines:
first_line = lines[0].strip()
first_line_clean = re.sub(r'[`\*]', '', first_line)
# Try to match number at start that's NOT followed by "/"
num_match = re.match(r'^(\d+\.?\d*)(\s*)', first_line_clean)
if num_match:
remaining = first_line_clean[len(num_match.group(0)):].strip()
if not remaining.startswith('/'):
try:
score_val = float(num_match.group(1))
except (ValueError, IndexError):
pass
# If not found and there's a "/", try to extract number before "/" (e.g., "3 / 5" -> 3)
if score_val is None and '/' in first_line_clean:
fraction_match = re.match(r'^\s*[`\*]*\s*(\d+\.?\d*)\s*[`\*]*\s*/\s*\d+', first_line_clean)
if fraction_match:
try:
score_val = float(fraction_match.group(1))
except (ValueError, IndexError):
pass
# If not found, try to find number after "score:" or "rating:"
if score_val is None:
score_match = re.search(r'(?:score|rating)\s*[:=]\s*(\d+\.?\d*)', section_content, re.IGNORECASE)
if score_match:
try:
score_val = float(score_match.group(1))
except (ValueError, IndexError):
pass
if score_val is not None:
review_dict["soundness"] = score_val # Keep as float
elif "presentation" in section_name_lower:
score_val = None
lines = section_content.split('\n')
if lines:
first_line = lines[0].strip()
first_line_clean = re.sub(r'[`\*]', '', first_line)
num_match = re.match(r'^(\d+\.?\d*)(\s*)', first_line_clean)
if num_match:
remaining = first_line_clean[len(num_match.group(0)):].strip()
if not remaining.startswith('/'):
try:
score_val = float(num_match.group(1))
except (ValueError, IndexError):
pass
if score_val is None and '/' in first_line_clean:
fraction_match = re.match(r'^\s*[`\*]*\s*(\d+\.?\d*)\s*[`\*]*\s*/\s*\d+', first_line_clean)
if fraction_match:
try:
score_val = float(fraction_match.group(1))
except (ValueError, IndexError):
pass
if score_val is None:
score_match = re.search(r'(?:score|rating)\s*[:=]\s*(\d+\.?\d*)', section_content, re.IGNORECASE)
if score_match:
try:
score_val = float(score_match.group(1))
except (ValueError, IndexError):
pass
if score_val is not None:
review_dict["presentation"] = score_val
elif "contribution" in section_name_lower:
score_val = None
lines = section_content.split('\n')
if lines:
first_line = lines[0].strip()
first_line_clean = re.sub(r'[`\*]', '', first_line)
num_match = re.match(r'^(\d+\.?\d*)(\s*)', first_line_clean)
if num_match:
remaining = first_line_clean[len(num_match.group(0)):].strip()
if not remaining.startswith('/'):
try:
score_val = float(num_match.group(1))
except (ValueError, IndexError):
pass
if score_val is None and '/' in first_line_clean:
fraction_match = re.match(r'^\s*[`\*]*\s*(\d+\.?\d*)\s*[`\*]*\s*/\s*\d+', first_line_clean)
if fraction_match:
try:
score_val = float(fraction_match.group(1))
except (ValueError, IndexError):
pass
if score_val is None:
score_match = re.search(r'(?:score|rating)\s*[:=]\s*(\d+\.?\d*)', section_content, re.IGNORECASE)
if score_match:
try:
score_val = float(score_match.group(1))
except (ValueError, IndexError):
pass
if score_val is not None:
review_dict["contribution"] = score_val
elif "strength" in section_name_lower:
review_dict["strengths"] = section_content
elif "weakness" in section_name_lower:
review_dict["weaknesses"] = section_content
elif "question" in section_name_lower:
review_dict["questions"] = section_content
elif "rating" in section_name_lower and "confidence" not in section_name_lower:
score_val = None
lines = section_content.split('\n')
if lines:
first_line = lines[0].strip()
first_line_clean = re.sub(r'[`\*]', '', first_line)
num_match = re.match(r'^(\d+\.?\d*)(\s*)', first_line_clean)
if num_match:
remaining = first_line_clean[len(num_match.group(0)):].strip()
if not remaining.startswith('/'):
try:
score_val = float(num_match.group(1))
except (ValueError, IndexError):
pass
if score_val is None and '/' in first_line_clean:
fraction_match = re.match(r'^\s*[`\*]*\s*(\d+\.?\d*)\s*[`\*]*\s*/\s*\d+', first_line_clean)
if fraction_match:
try:
score_val = float(fraction_match.group(1))
except (ValueError, IndexError):
pass
if score_val is None:
score_match = re.search(r'(?:score|rating)\s*[:=]\s*(\d+\.?\d*)', section_content, re.IGNORECASE)
if score_match:
try:
score_val = float(score_match.group(1))
except (ValueError, IndexError):
pass
if score_val is not None:
review_dict["rating"] = score_val
elif "confidence" in section_name_lower:
score_val = None
lines = section_content.split('\n')
if lines:
first_line = lines[0].strip()
first_line_clean = re.sub(r'[`\*]', '', first_line)
num_match = re.match(r'^(\d+\.?\d*)(\s*)', first_line_clean)
if num_match:
remaining = first_line_clean[len(num_match.group(0)):].strip()
if not remaining.startswith('/'):
try:
score_val = float(num_match.group(1))
except (ValueError, IndexError):
pass
if score_val is None and '/' in first_line_clean:
fraction_match = re.match(r'^\s*[`\*]*\s*(\d+\.?\d*)\s*[`\*]*\s*/\s*\d+', first_line_clean)
if fraction_match:
try:
score_val = float(fraction_match.group(1))
except (ValueError, IndexError):
pass
if score_val is None:
score_match = re.search(r'(?:score|rating)\s*[:=]\s*(\d+\.?\d*)', section_content, re.IGNORECASE)
if score_match:
try:
score_val = float(score_match.group(1))
except (ValueError, IndexError):
pass
if score_val is not None:
review_dict["confidence"] = score_val
elif "decision" in section_name_lower:
review_dict["decision"] = section_content
return review_dict
|