Spaces:
Sleeping
Sleeping
fix(gpt): parse unfenced graph JSON responses
Browse files- scripts/graph_pred/api.py +15 -1
scripts/graph_pred/api.py
CHANGED
|
@@ -64,6 +64,20 @@ def prepare_chat_completion_payload(payload: dict) -> dict:
|
|
| 64 |
return payload
|
| 65 |
|
| 66 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
def encode_image(image_path: str, center_crop=False):
|
| 68 |
"""Resize and encode the image as base64"""
|
| 69 |
# load the image
|
|
@@ -178,7 +192,7 @@ def predict_graph_twomode(image_path, first_img_data=None, second_img_data=None,
|
|
| 178 |
# Extract the response
|
| 179 |
content = completion.choices[0].message.content
|
| 180 |
|
| 181 |
-
src =
|
| 182 |
print(src)
|
| 183 |
# Convert the JSON format to tree format
|
| 184 |
diffuse_tree = convert_format(src)
|
|
|
|
| 64 |
return payload
|
| 65 |
|
| 66 |
|
| 67 |
+
def parse_graph_response(content: str) -> dict:
|
| 68 |
+
"""Parse a graph JSON response with or without markdown fences."""
|
| 69 |
+
if not content:
|
| 70 |
+
raise ValueError("GPT response is empty.")
|
| 71 |
+
|
| 72 |
+
match = re.search(r"```(?:json)?\s*(.*?)\s*```", content, re.DOTALL)
|
| 73 |
+
json_text = match.group(1) if match else content
|
| 74 |
+
try:
|
| 75 |
+
return json_repair.loads(json_text)
|
| 76 |
+
except Exception as exc:
|
| 77 |
+
preview = content[:500].replace("\n", "\\n")
|
| 78 |
+
raise ValueError(f"Failed to parse GPT graph response: {preview}") from exc
|
| 79 |
+
|
| 80 |
+
|
| 81 |
def encode_image(image_path: str, center_crop=False):
|
| 82 |
"""Resize and encode the image as base64"""
|
| 83 |
# load the image
|
|
|
|
| 192 |
# Extract the response
|
| 193 |
content = completion.choices[0].message.content
|
| 194 |
|
| 195 |
+
src = parse_graph_response(content)
|
| 196 |
print(src)
|
| 197 |
# Convert the JSON format to tree format
|
| 198 |
diffuse_tree = convert_format(src)
|