naman1102 commited on
Commit
82d6e3b
·
1 Parent(s): 34139eb

Update analyzer.py

Browse files
Files changed (1) hide show
  1. analyzer.py +31 -8
analyzer.py CHANGED
@@ -32,17 +32,40 @@ def analyze_code(code: str) -> str:
32
 
33
  def parse_llm_json_response(response: str):
34
  try:
35
- # Extract only the substring between the first '{' and the last '}'
36
- print("DEBUGGGGG ::: ",response)
 
37
  start = response.find('{')
38
  end = response.rfind('}')
39
- if start != -1 and end != -1 and end > start:
40
- json_str = response[start:end+1]
41
- else:
42
- json_str = response
43
- # Replace single quotes with double quotes for JSON keys/values
44
- json_str = re.sub(r"(?<!\\)'", '"', json_str)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  return json.loads(json_str)
 
46
  except Exception as e:
47
  print("DEBUGGGGG error ::: ", e)
48
  return {"error": f"Failed to parse JSON: {e}", "raw": response}
 
32
 
33
  def parse_llm_json_response(response: str):
34
  try:
35
+ print("DEBUGGGGG ::: ", response)
36
+
37
+ # 1. Extract the JSON object part of the string
38
  start = response.find('{')
39
  end = response.rfind('}')
40
+ if start == -1 or end == -1 or end < start:
41
+ raise ValueError("No valid JSON object found in the response.")
42
+ json_str = response[start:end+1]
43
+
44
+ # 2. Replace single quotes used for keys/values with double quotes.
45
+ # This handles cases like {'key': 'value'}
46
+ json_str = re.sub(r"'", '"', json_str)
47
+
48
+ # 3. Find all string values and escape any unescaped double quotes inside them.
49
+ # This uses a function as the replacement in re.sub
50
+ def escape_inner_quotes(match):
51
+ # The match object gives us the full string matched by the regex.
52
+ # We take the part between the outer quotes (group 1)
53
+ # and replace any \" with a temporary unique placeholder.
54
+ # Then, we replace any remaining " with \", and finally
55
+ # restore the original escaped quotes.
56
+ inner_content = match.group(1)
57
+ placeholder = "___TEMP_QUOTE___"
58
+ inner_content = inner_content.replace('\\"', placeholder)
59
+ inner_content = inner_content.replace('"', '\\"')
60
+ inner_content = inner_content.replace(placeholder, '\\"')
61
+ return f'"{inner_content}"'
62
+
63
+ # This regex finds a double quote, captures everything until the next double quote,
64
+ # and then applies the function to that captured group.
65
+ json_str = re.sub(r'"(.*?)"', escape_inner_quotes, json_str)
66
+
67
  return json.loads(json_str)
68
+
69
  except Exception as e:
70
  print("DEBUGGGGG error ::: ", e)
71
  return {"error": f"Failed to parse JSON: {e}", "raw": response}