Spaces:
Sleeping

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

Update app/utils/validation.py

Browse files
Files changed (1) hide show
  1. app/utils/validation.py +47 -23
app/utils/validation.py CHANGED
@@ -1,15 +1,58 @@
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:
@@ -36,22 +79,9 @@ def _try_parse_json(raw: str) -> dict | 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",
@@ -61,7 +91,6 @@ def _parse_structured_text(raw: str) -> dict | None:
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+)",
@@ -76,8 +105,7 @@ def _parse_structured_text(raw: str) -> dict | None:
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)
@@ -86,7 +114,7 @@ def _parse_structured_text(raw: str) -> dict | None:
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,
@@ -102,7 +130,6 @@ def _parse_structured_text(raw: str) -> dict | None:
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
@@ -116,10 +143,8 @@ def extract_and_validate_json(raw_output: str) -> dict:
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
 
@@ -129,6 +154,5 @@ def extract_and_validate_json(raw_output: str) -> dict:
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()
 
1
  import json
2
  import re
3
 
4
+ from fastapi import UploadFile
5
+
6
  from app.config import settings
7
  from app.schemas import JudgeResult
8
 
9
 
10
+ # ---------------------------------------------------------------------------
11
+ # Input validation (used by main.py)
12
+ # ---------------------------------------------------------------------------
13
+
14
+ def validate_scenario(scenario: str | None, mode: str) -> str | None:
15
+ if mode == "text" and not scenario:
16
+ return "scenario is required for text mode"
17
+ if mode == "image_text" and not scenario:
18
+ return "scenario is required for image_text mode"
19
+ if mode == "image" and scenario:
20
+ return "scenario must NOT be supplied for image mode"
21
+ if scenario and len(scenario) > settings.max_scenario_length:
22
+ return f"scenario exceeds maximum length of {settings.max_scenario_length}"
23
+ return None
24
+
25
+
26
+ async def validate_image(image: UploadFile | None, mode: str) -> str | None:
27
+ if mode in ("image", "image_text") and image is None:
28
+ return "image is required for this mode"
29
+ if mode == "text" and image is not None:
30
+ return "image must NOT be supplied for text mode"
31
+
32
+ if image is not None:
33
+ if image.content_type not in settings.allowed_image_types:
34
+ return f"unsupported image type: {image.content_type}. Allowed: {settings.allowed_image_types}"
35
+
36
+ contents = await image.read()
37
+ await image.seek(0)
38
+
39
+ if len(contents) == 0:
40
+ return "uploaded image is empty"
41
+ if len(contents) > settings.max_image_size_bytes:
42
+ return f"image exceeds maximum size of {settings.max_image_size_bytes} bytes"
43
+
44
+ return None
45
+
46
+
47
+ # ---------------------------------------------------------------------------
48
+ # AI output parsing (JSON + structured text fallback)
49
+ # ---------------------------------------------------------------------------
50
+
51
  def _try_parse_json(raw: str) -> dict | None:
52
  """Attempt to extract and parse JSON from model output."""
53
  cleaned = raw.strip()
54
 
55
+ # Remove markdown code fences
56
  fence_pattern = r"^```(?:json)?\s*\n?(.*?)\n?\s*```$"
57
  match = re.match(fence_pattern, cleaned, re.DOTALL)
58
  if match:
 
79
 
80
 
81
  def _parse_structured_text(raw: str) -> dict | None:
82
+ """Parse markdown/structured text when JSON parsing fails."""
 
 
 
 
 
 
 
 
 
 
 
 
83
  result: dict = {}
84
 
 
85
  verdict_map = {
86
  "green flag": "GREEN_FLAG",
87
  "green_flag": "GREEN_FLAG",
 
91
  "red_flag": "RED_FLAG",
92
  }
93
 
 
94
  field_patterns = {
95
  "verdict": r"(?:\*\*)?verdict(?:\*\*)?\s*[:=]\s*(.+?)(?:\n|$)",
96
  "score": r"(?:\*\*)?score(?:\*\*)?\s*[:=]\s*(\d+)",
 
105
  if match:
106
  value = match.group(1).strip().strip("*").strip()
107
  if field == "verdict":
108
+ result[field] = verdict_map.get(value.lower(), value.upper())
 
109
  elif field == "score":
110
  try:
111
  result[field] = int(value)
 
114
  else:
115
  result[field] = value
116
 
117
+ # Extract reasons list
118
  reasons_match = re.search(
119
  r"(?:\*\*)?reasons(?:\*\*)?\s*[:=]?\s*\n((?:\s*[\*\-\•\d][\.\)]\s*.+\n?)+)",
120
  raw,
 
130
  if reasons:
131
  result["reasons"] = reasons
132
 
 
133
  required = {"verdict", "score", "title", "summary", "reasons", "vibe", "advice"}
134
  if required.issubset(result.keys()):
135
  return result
 
143
  Tries JSON first, then falls back to structured text parsing.
144
  Raises ValueError if neither approach produces valid output.
145
  """
 
146
  parsed = _try_parse_json(raw_output)
147
 
 
148
  if parsed is None:
149
  parsed = _parse_structured_text(raw_output)
150
 
 
154
  f"Raw length: {len(raw_output)}"
155
  )
156
 
 
157
  validated = JudgeResult.model_validate(parsed)
158
  return validated.model_dump()