Skip to content

Commit a1777e5

Browse files
Enhance batch result processing; add safe JSON parsing and improve error handling
1 parent 288d183 commit a1777e5

2 files changed

Lines changed: 42 additions & 14 deletions

File tree

batch_processing/batch_method.py

Lines changed: 41 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
from datetime import datetime
1919
from zoneinfo import ZoneInfo
2020
from typing import Any
21+
import re
2122

2223

2324
def get_client() -> OpenAI:
@@ -139,6 +140,27 @@ def get_batch_status(batch_id: str) -> Any:
139140
return client.batches.retrieve(batch_id)
140141

141142

143+
# Extract classification results from the API responses
144+
def _safe_parse_model_text(s: str):
145+
t = s.strip()
146+
# strip ```json fences if present
147+
if t.startswith("```"):
148+
t = re.sub(r"^```(?:json)?\s*", "", t)
149+
t = re.sub(r"\s*```$", "", t)
150+
try:
151+
return json.loads(t), None
152+
except Exception:
153+
# try to repair {"label":"disapproval
154+
m = re.match(r'^\{"label":"([^"}\n]+)', t)
155+
if m:
156+
return {"label": m.group(1)}, "Truncated JSON repaired"
157+
# try label: disapproval
158+
m2 = re.match(r'^\s*label\s*[:=]\s*"?([^"}\n]+)"?\s*$', t, flags=re.I)
159+
if m2:
160+
return {"label": m2.group(1)}, "Non-JSON label recovered"
161+
return None, f"Unparsable JSON text: {t[:80]}"
162+
163+
142164
def get_batch_results(batch_id: str) -> None:
143165
"""
144166
Download and save the results of a completed batch processing job.
@@ -173,18 +195,28 @@ def get_batch_results(batch_id: str) -> None:
173195
if line.strip()
174196
]
175197

176-
# Extract classification results from the API responses
177-
responses = []
198+
responses, bad_rows = [], []
199+
178200
for res in results:
179-
text_output = res['response']['body']['output'][0]['content'][0]['text']
180-
text_output_converted = json.loads(text_output)
181-
metadata = res['response']['body']['metadata']
182-
combined = {**metadata, **text_output_converted} # Merge dictionaries
201+
body = res['response']['body']
202+
text_output = body['output'][0]['content'][0]['text']
203+
parsed, note = _safe_parse_model_text(text_output)
204+
205+
if parsed is None:
206+
bad_rows.append({
207+
"custom_id": res.get("custom_id"),
208+
"quote": body.get("metadata", {}).get("quote", ""),
209+
"raw_text": text_output
210+
})
211+
continue
212+
213+
metadata = body.get('metadata', {})
214+
combined = {"custom_id": res.get("custom_id"), **metadata, **parsed}
215+
if note:
216+
combined["repair_note"] = note
183217
responses.append(combined)
184218

185-
# Convert to DataFrame
186-
# df = pd.DataFrame(responses)
187-
# output = df.explode("label", ignore_index=True)
219+
# Now continue with your DF creation
188220
df = to_long_df(responses)
189221
save_as_csv(df)
190222

ui/batch_operations.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -53,11 +53,7 @@ def call_batch_download_async(parent: tk.Tk, batch_id: str) -> None:
5353
batch_id: Unique identifier of the batch job to download results from
5454
"""
5555
def _worker():
56-
try:
57-
batch_method.get_batch_results(batch_id)
58-
parent.after(0, lambda: print("Download finished for batch:", batch_id))
59-
except Exception as error:
60-
parent.after(0, lambda: messagebox.showerror("Download Error", str(error)))
56+
batch_method.get_batch_results(batch_id)
6157
threading.Thread(target=_worker, daemon=True).start()
6258

6359

0 commit comments

Comments
 (0)