"""Clean up a model's JSON answer after decoding. collapse_loops: a small model sometimes keeps writing table rows after the real table ends, by repeating a block of rows it already wrote. Real documents do have identical rows (the same item rung up several times), so only a clear loop is collapsed: - a block of 2+ rows that appears 3+ times in a row, or - a single row that appears 8+ times in a row (well above the longest real run, 5). One copy of the block is kept; the repeats, and a partial copy at the end, are dropped. Lists nested inside rows are cleaned the same way. """ import json MIN_BLOCK_REPEATS = 3 # block of 2+ rows: occurrences in a row that count as a loop MIN_SINGLE_REPEATS = 8 # single row: occurrences in a row that count as a loop MAX_PERIOD = 64 def _key(row): return json.dumps(row, sort_keys=True, ensure_ascii=False) def collapse_loops(rows): s = [_key(r) for r in rows] out, i = [], 0 while i < len(s): nxt = None for k in range(1, min(MAX_PERIOD, len(s) - i) + 1): need = MIN_SINGLE_REPEATS if k == 1 else MIN_BLOCK_REPEATS if i + need * k > len(s): continue # too few rows left for this period (a shorter one may still need fewer repeats) block = s[i:i + k] reps = 1 while s[i + reps * k:i + (reps + 1) * k] == block: reps += 1 if reps >= need: j = i + reps * k m = 0 while j + m < len(s) and m < k and s[j + m] == block[m]: m += 1 # a partial copy of the block at the end of the loop out.extend(rows[i:i + k]) nxt = j + m break if nxt is None: # no loop starts here out.append(rows[i]) nxt = i + 1 i = nxt return out def clean(value): """Collapse row loops in every list of objects inside a parsed answer. Returns (cleaned, rows_removed).""" removed = 0 def walk(v): nonlocal removed if isinstance(v, dict): return {k: walk(x) for k, x in v.items()} if isinstance(v, list): v = [walk(x) for x in v] if v and all(isinstance(x, dict) for x in v): c = collapse_loops(v) removed += len(v) - len(c) return c return v return v return walk(value), removed def clean_reply(text): """Clean a JSON reply string. Unparseable replies (e.g. cut off at the token limit) are returned unchanged.""" try: parsed = json.loads(text) except (json.JSONDecodeError, TypeError): return text, 0 cleaned, removed = clean(parsed) return (json.dumps(cleaned, ensure_ascii=False) if removed else text), removed