Spaces:
Sleeping

PERDYPTO commited on
Commit
ed5c92e
·
verified ·
1 Parent(s): e815922

Update app/utils/validation.py

Browse files
Files changed (1) hide show
  1. app/utils/validation.py +112 -36
app/utils/validation.py CHANGED
@@ -1,58 +1,134 @@
1
  import json
2
  import re
3
- from fastapi import UploadFile
4
  from app.config import settings
5
  from app.schemas import JudgeResult
6
 
7
 
8
- def validate_scenario(scenario: str | None, mode: str) -> str | None:
9
- if mode == "text" and not scenario:
10
- return "scenario is required for text mode"
11
- if mode == "image_text" and not scenario:
12
- return "scenario is required for image_text mode"
13
- if mode == "image" and scenario:
14
- return "scenario must NOT be supplied for image mode"
15
- if scenario and len(scenario) > settings.max_scenario_length:
16
- return f"scenario exceeds maximum length of {settings.max_scenario_length}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  return None
18
 
19
 
20
- async def validate_image(image: UploadFile | None, mode: str) -> str | None:
21
- if mode in ("image", "image_text") and image is None:
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
- if image is not None:
27
- if image.content_type not in settings.allowed_image_types:
28
- return f"unsupported image type: {image.content_type}. Allowed: {settings.allowed_image_types}"
 
 
 
 
 
 
 
 
 
29
 
30
- contents = await image.read()
31
- await image.seek(0) # Reset stream for later reading
 
 
 
 
 
 
 
32
 
33
- if len(contents) == 0:
34
- return "uploaded image is empty"
35
- if len(contents) > settings.max_image_size_bytes:
36
- return f"image exceeds maximum size of {settings.max_image_size_bytes} bytes"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
  return None
39
 
40
 
41
  def extract_and_validate_json(raw_output: str) -> dict:
42
- """Safely extract JSON from model output, handling markdown fences."""
43
- cleaned = raw_output.strip()
44
 
45
- # Remove markdown code fences if present
46
- fence_pattern = r"^```(?:json)?\s*\n?(.*?)\n?\s*```$"
47
- match = re.match(fence_pattern, cleaned, re.DOTALL)
48
- if match:
49
- cleaned = match.group(1).strip()
50
 
51
- try:
52
- parsed = json.loads(cleaned)
53
- except json.JSONDecodeError as e:
54
- raise ValueError(f"Model returned invalid JSON: {e}")
 
 
 
 
 
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()