PERDYPTO commited on
Update app/utils/validation.py
Browse files- app/utils/validation.py +112 -36
app/utils/validation.py
CHANGED
|
@@ -1,58 +1,134 @@
|
|
| 1 |
import json
|
| 2 |
import re
|
| 3 |
-
|
| 4 |
from app.config import settings
|
| 5 |
from app.schemas import JudgeResult
|
| 6 |
|
| 7 |
|
| 8 |
-
def
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
if
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
return None
|
| 18 |
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
return "image is required for this mode"
|
| 23 |
-
if mode == "text" and image is not None:
|
| 24 |
-
return "image must NOT be supplied for text mode"
|
| 25 |
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
return None
|
| 39 |
|
| 40 |
|
| 41 |
def extract_and_validate_json(raw_output: str) -> dict:
|
| 42 |
-
"""
|
| 43 |
-
cleaned = raw_output.strip()
|
| 44 |
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
-
# Validate against our schema
|
| 57 |
validated = JudgeResult.model_validate(parsed)
|
| 58 |
return validated.model_dump()
|
|
|
|
| 1 |
import json
|
| 2 |
import re
|
| 3 |
+
|
| 4 |
from app.config import settings
|
| 5 |
from app.schemas import JudgeResult
|
| 6 |
|
| 7 |
|
| 8 |
+
def _try_parse_json(raw: str) -> dict | None:
|
| 9 |
+
"""Attempt to extract and parse JSON from model output."""
|
| 10 |
+
cleaned = raw.strip()
|
| 11 |
+
|
| 12 |
+
# Remove markdown code fences if present
|
| 13 |
+
fence_pattern = r"^```(?:json)?\s*\n?(.*?)\n?\s*```$"
|
| 14 |
+
match = re.match(fence_pattern, cleaned, re.DOTALL)
|
| 15 |
+
if match:
|
| 16 |
+
cleaned = match.group(1).strip()
|
| 17 |
+
|
| 18 |
+
try:
|
| 19 |
+
parsed = json.loads(cleaned)
|
| 20 |
+
if isinstance(parsed, dict):
|
| 21 |
+
return parsed
|
| 22 |
+
except (json.JSONDecodeError, ValueError):
|
| 23 |
+
pass
|
| 24 |
+
|
| 25 |
+
# Try to find a JSON object embedded anywhere in the text
|
| 26 |
+
brace_match = re.search(r"\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}", cleaned, re.DOTALL)
|
| 27 |
+
if brace_match:
|
| 28 |
+
try:
|
| 29 |
+
parsed = json.loads(brace_match.group())
|
| 30 |
+
if isinstance(parsed, dict):
|
| 31 |
+
return parsed
|
| 32 |
+
except (json.JSONDecodeError, ValueError):
|
| 33 |
+
pass
|
| 34 |
+
|
| 35 |
return None
|
| 36 |
|
| 37 |
|
| 38 |
+
def _parse_structured_text(raw: str) -> dict | None:
|
| 39 |
+
"""Parse markdown/structured text output as fallback when JSON fails.
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
+
Handles formats like:
|
| 42 |
+
Verdict: YELLOW_FLAG
|
| 43 |
+
Score: 50
|
| 44 |
+
Title: Some Title
|
| 45 |
+
Summary: Some summary
|
| 46 |
+
Reasons:
|
| 47 |
+
* Reason one
|
| 48 |
+
* Reason two
|
| 49 |
+
Vibe: Some vibe
|
| 50 |
+
Advice: Some advice
|
| 51 |
+
"""
|
| 52 |
+
result: dict = {}
|
| 53 |
|
| 54 |
+
# Normalize common verdict variations
|
| 55 |
+
verdict_map = {
|
| 56 |
+
"green flag": "GREEN_FLAG",
|
| 57 |
+
"green_flag": "GREEN_FLAG",
|
| 58 |
+
"yellow flag": "YELLOW_FLAG",
|
| 59 |
+
"yellow_flag": "YELLOW_FLAG",
|
| 60 |
+
"red flag": "RED_FLAG",
|
| 61 |
+
"red_flag": "RED_FLAG",
|
| 62 |
+
}
|
| 63 |
|
| 64 |
+
# Extract single-value fields
|
| 65 |
+
field_patterns = {
|
| 66 |
+
"verdict": r"(?:\*\*)?verdict(?:\*\*)?\s*[:=]\s*(.+?)(?:\n|$)",
|
| 67 |
+
"score": r"(?:\*\*)?score(?:\*\*)?\s*[:=]\s*(\d+)",
|
| 68 |
+
"title": r"(?:\*\*)?title(?:\*\*)?\s*[:=]\s*(.+?)(?:\n|$)",
|
| 69 |
+
"summary": r"(?:\*\*)?summary(?:\*\*)?\s*[:=]\s*(.+?)(?:\n|$)",
|
| 70 |
+
"vibe": r"(?:\*\*)?vibe(?:\*\*)?\s*[:=]\s*(.+?)(?:\n|$)",
|
| 71 |
+
"advice": r"(?:\*\*)?advice(?:\*\*)?\s*[:=]\s*(.+?)(?:\n|$)",
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
for field, pattern in field_patterns.items():
|
| 75 |
+
match = re.search(pattern, raw, re.IGNORECASE)
|
| 76 |
+
if match:
|
| 77 |
+
value = match.group(1).strip().strip("*").strip()
|
| 78 |
+
if field == "verdict":
|
| 79 |
+
normalized = verdict_map.get(value.lower(), value.upper())
|
| 80 |
+
result[field] = normalized
|
| 81 |
+
elif field == "score":
|
| 82 |
+
try:
|
| 83 |
+
result[field] = int(value)
|
| 84 |
+
except ValueError:
|
| 85 |
+
pass
|
| 86 |
+
else:
|
| 87 |
+
result[field] = value
|
| 88 |
+
|
| 89 |
+
# Extract reasons list (bullet points or numbered items after "Reasons:")
|
| 90 |
+
reasons_match = re.search(
|
| 91 |
+
r"(?:\*\*)?reasons(?:\*\*)?\s*[:=]?\s*\n((?:\s*[\*\-\•\d][\.\)]\s*.+\n?)+)",
|
| 92 |
+
raw,
|
| 93 |
+
re.IGNORECASE,
|
| 94 |
+
)
|
| 95 |
+
if reasons_match:
|
| 96 |
+
reasons_block = reasons_match.group(1)
|
| 97 |
+
reasons = []
|
| 98 |
+
for line in reasons_block.strip().split("\n"):
|
| 99 |
+
cleaned_line = re.sub(r"^\s*[\*\-\•\d][\.\)]\s*", "", line).strip()
|
| 100 |
+
if cleaned_line:
|
| 101 |
+
reasons.append(cleaned_line)
|
| 102 |
+
if reasons:
|
| 103 |
+
result["reasons"] = reasons
|
| 104 |
+
|
| 105 |
+
# Only return if we got the minimum required fields
|
| 106 |
+
required = {"verdict", "score", "title", "summary", "reasons", "vibe", "advice"}
|
| 107 |
+
if required.issubset(result.keys()):
|
| 108 |
+
return result
|
| 109 |
|
| 110 |
return None
|
| 111 |
|
| 112 |
|
| 113 |
def extract_and_validate_json(raw_output: str) -> dict:
|
| 114 |
+
"""Extract valid JudgeResult from model output.
|
|
|
|
| 115 |
|
| 116 |
+
Tries JSON first, then falls back to structured text parsing.
|
| 117 |
+
Raises ValueError if neither approach produces valid output.
|
| 118 |
+
"""
|
| 119 |
+
# Attempt 1: Parse as JSON
|
| 120 |
+
parsed = _try_parse_json(raw_output)
|
| 121 |
|
| 122 |
+
# Attempt 2: Parse as structured markdown/text
|
| 123 |
+
if parsed is None:
|
| 124 |
+
parsed = _parse_structured_text(raw_output)
|
| 125 |
+
|
| 126 |
+
if parsed is None:
|
| 127 |
+
raise ValueError(
|
| 128 |
+
f"Could not parse model output as JSON or structured text. "
|
| 129 |
+
f"Raw length: {len(raw_output)}"
|
| 130 |
+
)
|
| 131 |
|
| 132 |
+
# Validate against our schema (this will raise ValidationError if invalid)
|
| 133 |
validated = JudgeResult.model_validate(parsed)
|
| 134 |
return validated.model_dump()
|