abhiimanyu commited on
Commit
8b39ec9
·
verified ·
1 Parent(s): 68edd2d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +16 -9
app.py CHANGED
@@ -31,10 +31,12 @@ def format_prompt(topic, description, difficulty):
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 attempts to auto-repair JSON output for learning content.
37
- Handles truncated and malformed JSON gracefully.
38
  """
39
  try:
40
  # Step 1: Clean the raw output
@@ -48,12 +50,17 @@ def clean_and_format_learning_content(output):
48
 
49
  # Step 2: Detect truncation and auto-repair
50
  if not cleaned_output.endswith("]}"):
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 sections array and root object
55
- else:
56
- cleaned_output += "]}" # Append both array and object closures
 
 
 
 
 
57
 
58
  # Step 3: Attempt to parse the cleaned JSON
59
  json_output = json.loads(cleaned_output)
@@ -71,7 +78,7 @@ def clean_and_format_learning_content(output):
71
  return json_output
72
 
73
  except (json.JSONDecodeError, ValueError) as e:
74
- # Return detailed error information
75
  return {
76
  "error": "Failed to parse or validate output as JSON",
77
  "details": str(e),
 
31
  return prompt
32
 
33
  # Function to clean and format the AI output
34
+ import json
35
+ import re
36
+
37
  def clean_and_format_learning_content(output):
38
  """
39
+ Cleans, validates, and repairs JSON output for learning content.
 
40
  """
41
  try:
42
  # Step 1: Clean the raw output
 
50
 
51
  # Step 2: Detect truncation and auto-repair
52
  if not cleaned_output.endswith("]}"):
53
+ # Count unmatched braces and brackets
54
+ open_braces = cleaned_output.count('{')
55
+ close_braces = cleaned_output.count('}')
56
+ open_brackets = cleaned_output.count('[')
57
+ close_brackets = cleaned_output.count(']')
58
+
59
+ # Add missing closing braces or brackets
60
+ if open_braces > close_braces:
61
+ cleaned_output += '}' * (open_braces - close_braces)
62
+ if open_brackets > close_brackets:
63
+ cleaned_output += ']' * (open_brackets - close_brackets)
64
 
65
  # Step 3: Attempt to parse the cleaned JSON
66
  json_output = json.loads(cleaned_output)
 
78
  return json_output
79
 
80
  except (json.JSONDecodeError, ValueError) as e:
81
+ # Return detailed error information for debugging
82
  return {
83
  "error": "Failed to parse or validate output as JSON",
84
  "details": str(e),