Spaces:
Running
Running
Update conver.py
Browse files
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 |
-
#
|
| 80 |
-
json_match = re.search(r'\{
|
| 81 |
if not json_match:
|
| 82 |
raise ValueError("No valid JSON object found in response")
|
| 83 |
json_str = json_match.group(0)
|
| 84 |
-
#
|
| 85 |
-
json_str =
|
| 86 |
-
json_str = re.sub(r'
|
| 87 |
-
json_str =
|
| 88 |
try:
|
| 89 |
dialogue = json.loads(json_str)
|
| 90 |
except json.JSONDecodeError as e:
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|