gnosticdev commited on
Commit
049c2dc
·
verified ·
1 Parent(s): 4b80b16

Update conver.py

Browse files
Files changed (1) hide show
  1. conver.py +12 -7
conver.py CHANGED
@@ -76,19 +76,24 @@ class URLToAudioConverter:
76
  response_content = response.choices[0].message.content
77
  # Clean response to ensure valid JSON
78
  response_content = response_content.strip()
79
- # Remove any leading/trailing non-JSON content
80
- json_match = re.search(r'\{.*\}', response_content, re.DOTALL)
81
  if not json_match:
82
  raise ValueError("No valid JSON object found in response")
83
  json_str = json_match.group(0)
84
- # Replace problematic characters and ensure proper JSON formatting
85
- json_str = json_str.replace('\n', '').replace('\r', '').replace('\t', '')
86
- json_str = re.sub(r',\s*}', '}', json_str) # Remove trailing commas
87
- json_str = re.sub(r',\s*,', ',', json_str) # Remove double commas
88
  try:
89
  dialogue = json.loads(json_str)
90
  except json.JSONDecodeError as e:
91
- raise ValueError(f"JSON parsing failed: {str(e)}")
 
 
 
 
 
92
  if not dialogue.get("conversation"):
93
  raise ValueError("No valid conversation generated")
94
  return dialogue
 
76
  response_content = response.choices[0].message.content
77
  # Clean response to ensure valid JSON
78
  response_content = response_content.strip()
79
+ # Extract valid JSON using regex
80
+ json_match = re.search(r'\{.*?\}\s*$', response_content, re.DOTALL)
81
  if not json_match:
82
  raise ValueError("No valid JSON object found in response")
83
  json_str = json_match.group(0)
84
+ # Clean problematic characters and fix common JSON issues
85
+ json_str = re.sub(r',\s*([\]}])', r'\1', json_str) # Remove trailing commas
86
+ json_str = re.sub(r'\s+', ' ', json_str) # Replace multiple spaces
87
+ json_str = json_str.replace('\\"', '"').replace('"{', '{').replace('}"', '}')
88
  try:
89
  dialogue = json.loads(json_str)
90
  except json.JSONDecodeError as e:
91
+ # Attempt to fix JSON by truncating at last valid object
92
+ last_valid = json_str[:json_str.rfind('}')+1]
93
+ try:
94
+ dialogue = json.loads(last_valid)
95
+ except json.JSONDecodeError as e2:
96
+ raise ValueError(f"JSON parsing failed: {str(e2)}")
97
  if not dialogue.get("conversation"):
98
  raise ValueError("No valid conversation generated")
99
  return dialogue