abhiimanyu commited on
Commit
b2c3e78
·
verified ·
1 Parent(s): c3b5ff4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +15 -24
app.py CHANGED
@@ -31,10 +31,9 @@ def format_prompt(topic, description, difficulty):
31
  return prompt
32
 
33
  # Function to clean and format the AI output
34
- def clean_and_format_output(output):
35
  """
36
- Cleans, validates, and attempts to auto-repair JSON output from the AI model.
37
- Handles truncated, malformed JSON and missing delimiters.
38
  """
39
  try:
40
  # Step 1: Clean the raw output
@@ -43,27 +42,19 @@ def clean_and_format_output(output):
43
  cleaned_output = re.sub(r'^[^{]*', '', cleaned_output) # Remove text before the first '{'
44
  cleaned_output = re.sub(r'[^}]*$', '', cleaned_output) # Remove text after the last '}'
45
  cleaned_output = re.sub(r'\s+', ' ', cleaned_output).strip() # Normalize whitespace
 
46
  cleaned_output = re.sub(r',\s*(\}|\])', r'\1', cleaned_output) # Remove trailing commas
47
 
48
- # Step 2: Attempt to auto-repair JSON
49
- if not cleaned_output.endswith("]}"):
50
- # Close the sections array and root object if needed
51
- if cleaned_output.endswith("]"):
52
- cleaned_output += "}" # Close the root object
53
- elif cleaned_output.endswith("}"):
54
- cleaned_output = cleaned_output[:-1] + "]}" # Close the array and root object
55
- else:
56
- cleaned_output += "]}" # Append both array and object closures
57
-
58
- # Step 3: Attempt to parse the cleaned output
59
- try:
60
- json_output = json.loads(cleaned_output)
61
- except json.JSONDecodeError as e:
62
- raise ValueError(f"JSON decoding error: {str(e)}")
63
-
64
- # Step 4: Validate required structure
65
- if "title" not in json_output or "sections" not in json_output:
66
- raise ValueError("Missing required keys: 'title' or 'sections'.")
67
  if not isinstance(json_output["sections"], list):
68
  raise ValueError("'sections' must be a list.")
69
  for section in json_output["sections"]:
@@ -72,8 +63,8 @@ def clean_and_format_output(output):
72
 
73
  return json_output
74
 
75
- except ValueError as e:
76
- # Return detailed error information
77
  return {
78
  "error": "Failed to parse or validate output as JSON",
79
  "details": str(e),
 
31
  return prompt
32
 
33
  # Function to clean and format the AI output
34
+ def clean_and_format_learning_content(output):
35
  """
36
+ Cleans, validates, and parses JSON output for learning content.
 
37
  """
38
  try:
39
  # Step 1: Clean the raw output
 
42
  cleaned_output = re.sub(r'^[^{]*', '', cleaned_output) # Remove text before the first '{'
43
  cleaned_output = re.sub(r'[^}]*$', '', cleaned_output) # Remove text after the last '}'
44
  cleaned_output = re.sub(r'\s+', ' ', cleaned_output).strip() # Normalize whitespace
45
+ cleaned_output = cleaned_output.replace('\\"', '"') # Fix improperly escaped quotes
46
  cleaned_output = re.sub(r',\s*(\}|\])', r'\1', cleaned_output) # Remove trailing commas
47
 
48
+ # Step 2: Attempt to parse the cleaned JSON
49
+ json_output = json.loads(cleaned_output)
50
+
51
+ # Step 3: Validate required keys
52
+ required_keys = ["title", "sections"]
53
+ for key in required_keys:
54
+ if key not in json_output:
55
+ raise ValueError(f"Missing key: {key}")
56
+
57
+ # Ensure "sections" is a list and has the required structure
 
 
 
 
 
 
 
 
 
58
  if not isinstance(json_output["sections"], list):
59
  raise ValueError("'sections' must be a list.")
60
  for section in json_output["sections"]:
 
63
 
64
  return json_output
65
 
66
+ except (json.JSONDecodeError, ValueError) as e:
67
+ # Return error details if parsing or validation fails
68
  return {
69
  "error": "Failed to parse or validate output as JSON",
70
  "details": str(e),