tracecomparekit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,717 @@
1
+ """Two editable Python functions, animated side by side.
2
+
3
+ Run: python -m difffinder.sorting_visualizer
4
+ Requires Python 3.9+ with Tkinter and the local difffinder package installed.
5
+ Only run code you trust: the worker process is NOT a security sandbox.
6
+ """
7
+
8
+ import ast
9
+ import difflib
10
+ import json
11
+ import math
12
+ from pathlib import Path
13
+ import random
14
+ import subprocess
15
+ import sys
16
+ import tempfile
17
+ import time
18
+ import traceback
19
+
20
+
21
+ # Both examples edit the list in place, which makes every change visible.
22
+ BUBBLE = '''def sort(arr):
23
+ # Compare neighbors and move the largest value to the end.
24
+ for end in range(len(arr) - 1, 0, -1):
25
+ swapped = False
26
+ for i in range(end):
27
+ if arr[i] > arr[i + 1]:
28
+ arr[i], arr[i + 1] = arr[i + 1], arr[i]
29
+ swapped = True
30
+ # An unchanged pass means the list is already sorted.
31
+ if not swapped:
32
+ break
33
+ return arr
34
+ '''
35
+
36
+ SELECTION = '''def sort(arr):
37
+ # Find the smallest remaining value for each position.
38
+ for i in range(len(arr)):
39
+ smallest = i
40
+ for j in range(i + 1, len(arr)):
41
+ if arr[j] < arr[smallest]:
42
+ smallest = j
43
+ if smallest != i:
44
+ arr[i], arr[smallest] = arr[smallest], arr[i]
45
+ return arr
46
+ '''
47
+
48
+ MAX_EVENTS = 20000
49
+ TIMEOUT_SECONDS = 8
50
+ USER_FILENAME = '<visualized_sort>'
51
+
52
+
53
+ def numeric_list(value):
54
+ """Only finite numbers can be drawn as bars."""
55
+ return (
56
+ isinstance(value, list)
57
+ and len(value) <= 100
58
+ and all(type(x) in (int, float) and math.isfinite(x)
59
+ and abs(x) <= 1_000_000 for x in value)
60
+ )
61
+
62
+
63
+ def analyze(source, name):
64
+ """Describe syntax without guessing what an algorithm means."""
65
+ tree = ast.parse(source)
66
+ functions = [n for n in tree.body if isinstance(n, ast.FunctionDef)]
67
+ if not functions:
68
+ raise ValueError('Define a regular function, for example: def sort(arr):')
69
+ selected = next((n for n in functions if n.name == name), None)
70
+ if selected is None:
71
+ raise ValueError(f'No top-level function named {name!r}. Update the function-name box.')
72
+ nodes = list(ast.walk(selected))
73
+ return {
74
+ 'parameters': ast.unparse(selected.args),
75
+ 'for loops': sum(isinstance(n, ast.For) for n in nodes),
76
+ 'while loops': sum(isinstance(n, ast.While) for n in nodes),
77
+ 'if statements': sum(isinstance(n, ast.If) for n in nodes),
78
+ 'calls': ', '.join(sorted({ast.unparse(n.func) for n in nodes
79
+ if isinstance(n, ast.Call)})) or 'none',
80
+ }
81
+
82
+
83
+ def compare_lines(source_a, source_b):
84
+ """Align source lines for native text widgets. No markup is generated.
85
+
86
+ Each row contains (line_number, text, color_tag) for A and B.
87
+ Blank placeholders keep insertions and removals aligned across panes.
88
+ """
89
+ lines_a, lines_b = source_a.splitlines(), source_b.splitlines()
90
+ rows = []
91
+ matcher = difflib.SequenceMatcher(None, lines_a, lines_b, autojunk=False)
92
+ for operation, a_start, a_end, b_start, b_end in matcher.get_opcodes():
93
+ count = max(a_end - a_start, b_end - b_start)
94
+ for offset in range(count):
95
+ a_index, b_index = a_start + offset, b_start + offset
96
+ left = (None, '', 'gap')
97
+ right = (None, '', 'gap')
98
+ if a_index < a_end:
99
+ tag = 'equal' if operation == 'equal' else 'removed' if operation == 'delete' else 'changed'
100
+ left = (a_index + 1, lines_a[a_index], tag)
101
+ if b_index < b_end:
102
+ tag = 'equal' if operation == 'equal' else 'added' if operation == 'insert' else 'changed'
103
+ right = (b_index + 1, lines_b[b_index], tag)
104
+ rows.append((left, right))
105
+ return rows
106
+
107
+
108
+ # ============================================================
109
+ # RECORDING ENGINE
110
+ # Runs in a separate process so slow code won't freeze the UI.
111
+ # sys.settrace observes Python lines; it does not rewrite your code.
112
+ # ============================================================
113
+
114
+ def record(source, name, values):
115
+ analysis = analyze(source, name)
116
+ events = []
117
+ state = {'root': None, 'argument': None, 'lines': 0, 'changes': 0}
118
+ deadline = time.monotonic() + TIMEOUT_SECONDS - 1
119
+ data = list(values)
120
+ namespace = {'__name__': '__visualized_code__'}
121
+
122
+ def append_event(line, event_name, frame=None, explicit=None):
123
+ # Watch the selected function's first argument, even inside helpers.
124
+ # If it is rebound to another list, follow the new list.
125
+ root = state['root']
126
+ watched = root.f_locals.get(state['argument'], data) if root else data
127
+ if explicit is not None:
128
+ watched = explicit
129
+ if not numeric_list(watched):
130
+ raise ValueError('The watched argument must remain a list of up to 100 finite numbers.')
131
+ snapshot = list(watched)
132
+ previous = events[-1]['values'] if events else snapshot
133
+ changed = [i for i, value in enumerate(snapshot)
134
+ if i >= len(previous) or previous[i] != value]
135
+ if snapshot != previous:
136
+ state['changes'] += 1
137
+ # Show simple local values such as i, j, end and smallest.
138
+ local_values = {}
139
+ if frame is not None:
140
+ for key, value in frame.f_locals.items():
141
+ if type(value) in (int, float, bool, str) and len(repr(value)) < 60:
142
+ local_values[key] = repr(value)
143
+ if len(local_values) >= 8:
144
+ break
145
+ events.append({'values': snapshot, 'line': line, 'event': event_name,
146
+ 'changed': changed, 'locals': local_values})
147
+
148
+ def tracer(frame, event, argument):
149
+ if time.monotonic() > deadline:
150
+ raise TimeoutError('Recording took too long. Try a smaller input.')
151
+ if frame.f_code.co_filename != USER_FILENAME:
152
+ return None
153
+ if event == 'call' and state['root'] is None and frame.f_code is target.__code__:
154
+ state['root'] = frame
155
+ state['argument'] = frame.f_code.co_varnames[0]
156
+ if event == 'line':
157
+ state['lines'] += 1
158
+ if state['lines'] > MAX_EVENTS:
159
+ raise RuntimeError(f'More than {MAX_EVENTS:,} Python line events. Try fewer numbers.')
160
+ # Line events happen BEFORE the highlighted line executes.
161
+ append_event(frame.f_lineno, 'Next line', frame)
162
+ return tracer
163
+
164
+ try:
165
+ # User code executes with normal Python permissions in this worker.
166
+ # The parent also enforces a timeout, including top-level code here.
167
+ exec(compile(source, USER_FILENAME, 'exec'), namespace)
168
+ target = namespace.get(name)
169
+ if not callable(target) or not hasattr(target, '__code__'):
170
+ raise ValueError('The selected name must refer to a Python function.')
171
+ append_event(None, 'Initial input')
172
+ sys.settrace(tracer)
173
+ try:
174
+ result = target(data)
175
+ finally:
176
+ sys.settrace(None)
177
+ # Support either sorting in place (return None) or returning a list.
178
+ output = data if result is None else result
179
+ if not numeric_list(output):
180
+ raise ValueError('Return a numeric list, or modify the input list and return None.')
181
+ append_event(None, 'Finished', explicit=output)
182
+ return {'events': events, 'analysis': analysis, 'lines': state['lines'],
183
+ 'changes': state['changes'], 'output': list(output),
184
+ 'sorted': output == sorted(values), 'error': None}
185
+ except BaseException:
186
+ sys.settrace(None)
187
+ return {'events': events, 'analysis': analysis, 'lines': state['lines'],
188
+ 'changes': state['changes'], 'error': traceback.format_exc(limit=5)}
189
+ finally:
190
+ # Drop references to frames after recording.
191
+ state['root'] = None
192
+
193
+
194
+ def compare_sources(snapshots, values):
195
+ """Compare the selected functions without changing animation semantics."""
196
+ import linecache
197
+ from difffinder import compare_traces
198
+
199
+ functions = []
200
+ filenames = []
201
+ try:
202
+ for index, (source, name) in enumerate(snapshots):
203
+ analyze(source, name)
204
+ filename = f'<difffinder_visualizer_{index}>'
205
+ filenames.append(filename)
206
+ linecache.cache[filename] = (len(source), None, source.splitlines(True), filename)
207
+ namespace = {'__name__': '__visualized_code__'}
208
+ exec(compile(source, filename, 'exec'), namespace)
209
+ functions.append(namespace[name])
210
+ result = compare_traces(*functions, args=(list(values),), probe=False, max_steps=MAX_EVENTS)
211
+ return {'report': str(result), 'same': result.same}
212
+ finally:
213
+ for filename in filenames:
214
+ linecache.cache.pop(filename, None)
215
+
216
+
217
+ def worker(request_path, response_path):
218
+ """Read a job and write a result; printing in user code stays out of the UI."""
219
+ try:
220
+ request = json.loads(Path(request_path).read_text(encoding='utf-8'))
221
+ if 'snapshots' in request:
222
+ response = compare_sources(request['snapshots'], request['values'])
223
+ else:
224
+ response = record(request['source'], request['name'], request['values'])
225
+ except BaseException:
226
+ response = {'error': traceback.format_exc(limit=5), 'events': []}
227
+ Path(response_path).write_text(json.dumps(response), encoding='utf-8')
228
+
229
+
230
+ # ============================================================
231
+ # DESKTOP UI
232
+ # Tkinter is imported only here so the recorder can run headlessly.
233
+ # ============================================================
234
+
235
+ def launch_app():
236
+ import tkinter as tk
237
+ from tkinter import messagebox, ttk
238
+ from tkinter.scrolledtext import ScrolledText
239
+
240
+ class DiffPanel(ttk.Frame):
241
+ """A read-only, synchronized code comparison inside the main window."""
242
+
243
+ def __init__(self, parent):
244
+ super().__init__(parent, padding=8)
245
+ ttk.Label(self, text='Code differences', font=('', 16, 'bold')).pack(anchor='w')
246
+ ttk.Label(self, text='Red: removed from A • Green: added in B • Yellow: changed lines'
247
+ '\nCompares the current code boxes. Return to “Code & animation” to edit them.').pack(anchor='w', pady=6)
248
+ self.description = tk.StringVar()
249
+ ttk.Label(self, textvariable=self.description).pack(anchor='w', pady=(0, 8))
250
+ grid = ttk.Frame(self)
251
+ grid.pack(fill='both', expand=True)
252
+ grid.rowconfigure(1, weight=1)
253
+ for column in (0, 1):
254
+ grid.columnconfigure(column, weight=1, uniform='code')
255
+ ttk.Label(grid, text=f"Function {'A' if column == 0 else 'B'}",
256
+ font=('', 12, 'bold')).grid(row=0, column=column, sticky='w', pady=5)
257
+ self.texts = []
258
+ self.syncing = False
259
+ self.scrollbar = ttk.Scrollbar(grid, orient='vertical', command=self.scroll_both)
260
+ self.scrollbar.grid(row=1, column=2, sticky='ns')
261
+ for column in (0, 1):
262
+ text = tk.Text(grid, wrap='none', font=('Courier', 12), width=40,
263
+ background='#f8fafc', foreground='#111827',
264
+ selectbackground='#bfdbfe', selectforeground='#111827',
265
+ borderwidth=1, relief='solid', padx=6, pady=6)
266
+ text.grid(row=1, column=column, sticky='nsew', padx=(0, 5))
267
+ horizontal = ttk.Scrollbar(grid, orient='horizontal', command=text.xview)
268
+ horizontal.grid(row=2, column=column, sticky='ew', padx=(0, 5))
269
+ text.configure(xscrollcommand=horizontal.set)
270
+ for tag, color in [('removed', '#fee2e2'), ('added', '#dcfce7'),
271
+ ('changed', '#fef3c7'), ('gap', '#e2e8f0')]:
272
+ text.tag_configure(tag, background=color)
273
+ text.configure(state='disabled',
274
+ yscrollcommand=lambda first, last, index=column: self.sync_scroll(index, first, last))
275
+ self.texts.append(text)
276
+
277
+ def scroll_both(self, *arguments):
278
+ # The shared scrollbar moves both panes by the same amount.
279
+ for text in self.texts:
280
+ text.yview(*arguments)
281
+
282
+ def sync_scroll(self, index, first, last):
283
+ # Also synchronize mouse-wheel and keyboard scrolling in either pane.
284
+ if self.syncing or len(self.texts) != 2:
285
+ return
286
+ self.syncing = True
287
+ try:
288
+ self.scrollbar.set(first, last)
289
+ other = self.texts[1 - index]
290
+ if abs(other.yview()[0] - float(first)) > 0.000001:
291
+ other.yview_moveto(first)
292
+ finally:
293
+ self.syncing = False
294
+
295
+ def refresh(self, source_a, source_b):
296
+ rows = compare_lines(source_a, source_b)
297
+ affected = [0, 0]
298
+ self.syncing = True
299
+ try:
300
+ for side, text in enumerate(self.texts):
301
+ text.configure(state='normal')
302
+ text.delete('1.0', 'end')
303
+ for row in rows:
304
+ number, content, tag = row[side]
305
+ # Line numbers refer to the ORIGINAL input, not aligned rows.
306
+ prefix = f'{number:4} ' if number is not None else ' '
307
+ text.insert('end', prefix + content + '\n', tag)
308
+ if tag in ('removed', 'added', 'changed'):
309
+ affected[side] += 1
310
+ text.configure(state='disabled')
311
+ text.yview_moveto(0)
312
+ text.xview_moveto(0)
313
+ finally:
314
+ self.syncing = False
315
+ if not any(affected):
316
+ self.description.set('No line differences found.')
317
+ else:
318
+ self.description.set(f'A: {affected[0]} affected lines • B: {affected[1]} affected lines')
319
+
320
+ class SortPanel(ttk.Frame):
321
+ def __init__(self, parent, title, source, color):
322
+ super().__init__(parent, padding=8)
323
+ self.color = color
324
+ self.result = None
325
+ self.last_event = None
326
+ self.position = 0
327
+ self.visible_events = []
328
+ self.name = tk.StringVar(value='sort')
329
+ ttk.Label(self, text=title, font=('', 16, 'bold')).pack(anchor='w')
330
+ name_row = ttk.Frame(self)
331
+ name_row.pack(fill='x', pady=5)
332
+ ttk.Label(name_row, text='Function to run:').pack(side='left')
333
+ ttk.Entry(name_row, textvariable=self.name, width=18).pack(side='left', padx=8)
334
+ self.editor = ScrolledText(self, height=15, width=48, undo=True,
335
+ font=('Courier', 12), wrap='none')
336
+ self.editor.pack(fill='both', expand=True)
337
+ self.editor.insert('1.0', source)
338
+ self.editor.tag_configure('current', background='#fff0a6', foreground='#111111')
339
+ # Insert four spaces when Tab is pressed in the code editor.
340
+ self.editor.bind('<Tab>', self.indent)
341
+ self.canvas = tk.Canvas(self, height=205, bg='#111827', highlightthickness=0)
342
+ self.canvas.pack(fill='x', pady=(10, 5))
343
+ self.canvas.bind('<Configure>', lambda event: self.redraw())
344
+ self.caption = tk.StringVar(value='Paste Python code above, then click Compare & Record.')
345
+ ttk.Label(self, textvariable=self.caption, wraplength=550).pack(anchor='w')
346
+ self.locals_text = tk.StringVar(value=' ')
347
+ ttk.Label(self, textvariable=self.locals_text, wraplength=550).pack(anchor='w')
348
+
349
+ def indent(self, event):
350
+ self.editor.insert('insert', ' ')
351
+ return 'break'
352
+
353
+ def source(self):
354
+ return self.editor.get('1.0', 'end-1c')
355
+
356
+ def reset(self, values):
357
+ self.result = None
358
+ self.visible_events = []
359
+ self.position = 0
360
+ self.editor.tag_remove('current', '1.0', 'end')
361
+ self.last_event = {'values': values, 'changed': [], 'event': 'Initial input'}
362
+ self.redraw()
363
+
364
+ def set_filter(self, changes_only):
365
+ events = self.result.get('events', []) if self.result else []
366
+ # Keep start/end and any event where the list actually changed.
367
+ self.visible_events = [e for i, e in enumerate(events)
368
+ if not changes_only or i == 0 or i == len(events) - 1
369
+ or e['values'] != events[i - 1]['values']]
370
+ self.position = 0
371
+ if self.visible_events:
372
+ self.show(0)
373
+
374
+ def show(self, position):
375
+ self.position = min(position, len(self.visible_events) - 1)
376
+ event = self.visible_events[self.position]
377
+ self.last_event = event
378
+ self.editor.tag_remove('current', '1.0', 'end')
379
+ line = event.get('line')
380
+ if line:
381
+ self.editor.tag_add('current', f'{line}.0', f'{line}.end')
382
+ self.editor.see(f'{line}.0')
383
+ suffix = f' — next line: {line}' if line else ''
384
+ self.caption.set(f"Frame {self.position + 1}/{len(self.visible_events)}"
385
+ f" — {event['event']}{suffix}")
386
+ self.locals_text.set(' '.join(f'{k}={v}' for k, v in event.get('locals', {}).items()) or ' ')
387
+ self.redraw()
388
+
389
+ def redraw(self):
390
+ self.canvas.delete('all')
391
+ if not self.last_event:
392
+ return
393
+ values = self.last_event['values']
394
+ width = max(self.canvas.winfo_width(), 100)
395
+ height = max(self.canvas.winfo_height(), 100)
396
+ if not values:
397
+ self.canvas.create_text(width / 2, height / 2, text='Empty list []', fill='white')
398
+ return
399
+ # Both panels use the SAME scale, including for negative values.
400
+ low, high = app.bounds
401
+ span = high - low or 1
402
+ def y(value):
403
+ return 22 + (high - value) / span * (height - 52)
404
+ baseline = y(0)
405
+ self.canvas.create_line(10, baseline, width - 10, baseline, fill='#64748b')
406
+ cell = (width - 20) / len(values)
407
+ changed = set(self.last_event.get('changed', []))
408
+ finished = self.last_event.get('event') == 'Finished' and self.result and self.result.get('sorted')
409
+ for index, value in enumerate(values):
410
+ left = 10 + index * cell + 1
411
+ right = 10 + (index + 1) * cell - 1
412
+ fill = '#4ade80' if finished else '#fbbf24' if index in changed else self.color
413
+ top, bottom = sorted((baseline, y(value)))
414
+ self.canvas.create_rectangle(left, top, right, max(bottom, top + 2), fill=fill, outline='')
415
+ if cell >= 24:
416
+ self.canvas.create_text((left + right) / 2, height - 13,
417
+ text=f'{value:g}', fill='#e2e8f0', font=('', 9))
418
+
419
+ class App:
420
+ def __init__(self, root):
421
+ self.root = root
422
+ self.jobs = []
423
+ self.scratch = None
424
+ self.playing = False
425
+ self.timer = None
426
+ self.bounds = (0, 100)
427
+ self.snapshots = []
428
+ self.recorded_input = None
429
+ root.title('DiffFinder Sorting Visualizer')
430
+ root.geometry('1220x900')
431
+ root.minsize(900, 700)
432
+ root.protocol('WM_DELETE_WINDOW', self.close)
433
+ wrapper = ttk.Frame(root, padding=12)
434
+ wrapper.pack(fill='both', expand=True)
435
+ ttk.Label(wrapper, text='Paste two sorting functions. Watch the same input change.',
436
+ font=('', 17, 'bold')).pack(anchor='w')
437
+ ttk.Label(wrapper, text='Run only code you trust. Each function receives one list; '
438
+ 'modify it in place or return a new list.').pack(anchor='w', pady=(4, 10))
439
+ controls = ttk.Frame(wrapper)
440
+ controls.pack(fill='x')
441
+ ttk.Label(controls, text='Input numbers:').pack(side='left')
442
+ self.input = tk.StringVar(value='42, 17, 8, 63, 29, 51, 4, 36, 22, 75, 12, 58')
443
+ ttk.Entry(controls, textvariable=self.input).pack(side='left', fill='x', expand=True, padx=8)
444
+ ttk.Button(controls, text='Random input', command=self.randomize).pack(side='left')
445
+ self.record_button = ttk.Button(controls, text='Compare & Record', command=self.start)
446
+ self.record_button.pack(side='left', padx=(8, 0))
447
+ self.cancel_button = ttk.Button(controls, text='Cancel', command=self.cancel, state='disabled')
448
+ self.cancel_button.pack(side='left', padx=(8, 0))
449
+ # Both views are native Tkinter tabs in the same Python window.
450
+ self.tabs = ttk.Notebook(wrapper)
451
+ self.tabs.pack(fill='both', expand=True, pady=8)
452
+ self.animation_tab = ttk.Frame(self.tabs)
453
+ self.diff_tab = DiffPanel(self.tabs)
454
+ self.tabs.add(self.animation_tab, text='Code & animation')
455
+ self.tabs.add(self.diff_tab, text='Code differences')
456
+ self.comparison_tab = ttk.Frame(self.tabs, padding=8)
457
+ self.tabs.add(self.comparison_tab, text='DiffFinder comparison')
458
+ ttk.Label(self.comparison_tab, text='A is the candidate; B is the reference. '
459
+ 'Compares return values, exceptions and input mutations on this input.\n'
460
+ 'Functions run again for this comparison; automatic input probing is off.').pack(anchor='w')
461
+ self.comparison_text = ScrolledText(self.comparison_tab, wrap='word', font=('Courier', 12))
462
+ self.comparison_text.pack(fill='both', expand=True, pady=8)
463
+ self.set_comparison('Click Compare & Record to see the DiffFinder report.')
464
+ columns = ttk.Panedwindow(self.animation_tab, orient='horizontal')
465
+ columns.pack(fill='both', expand=True)
466
+ self.panels = [SortPanel(columns, 'Function A', BUBBLE, '#38bdf8'),
467
+ SortPanel(columns, 'Function B', SELECTION, '#a78bfa')]
468
+ for panel in self.panels:
469
+ columns.add(panel, weight=1)
470
+ playback = ttk.Frame(wrapper)
471
+ playback.pack(fill='x', pady=5)
472
+ self.play_button = ttk.Button(playback, text='Play', command=self.play)
473
+ self.play_button.pack(side='left')
474
+ ttk.Button(playback, text='Pause', command=self.pause).pack(side='left', padx=5)
475
+ ttk.Button(playback, text='Step', command=self.step_once).pack(side='left')
476
+ ttk.Button(playback, text='Restart', command=self.restart).pack(side='left', padx=5)
477
+ self.changes_only = tk.BooleanVar(value=True)
478
+ ttk.Checkbutton(playback, text='Only list changes', variable=self.changes_only,
479
+ command=self.refilter).pack(side='left', padx=8)
480
+ ttk.Label(playback, text='Frames/sec').pack(side='left')
481
+ self.speed = tk.DoubleVar(value=8)
482
+ ttk.Scale(playback, from_=1, to=40, variable=self.speed, length=130).pack(side='left', padx=5)
483
+ ttk.Button(playback, text='View code diff', command=self.show_diff).pack(side='right')
484
+ self.status = tk.StringVar(value='Ready. Edit either code box and click Compare & Record.')
485
+ ttk.Label(wrapper, textvariable=self.status, wraplength=1120).pack(anchor='w', pady=5)
486
+ self.summary = ScrolledText(wrapper, height=6, wrap='word', font=('Courier', 11))
487
+ self.summary.pack(fill='x')
488
+ self.summary.insert('1.0', 'Yellow bars changed since the previous recorded line. '
489
+ 'Green means the final result matches ascending sorted(input).\n'
490
+ 'The highlighted line executes NEXT. Uncheck “Only list changes” '
491
+ 'to step through every Python line.\n'
492
+ 'Built-in sorted()/list.sort() execute internally, so their internal '
493
+ 'steps are not visible. Write the sorting loop in Python for animation.')
494
+ self.summary.configure(state='disabled')
495
+ self.tabs.bind('<<NotebookTabChanged>>', self.tab_changed)
496
+
497
+ def randomize(self):
498
+ self.input.set(', '.join(map(str, random.sample(range(1, 100), 18))))
499
+
500
+ def set_comparison(self, report):
501
+ self.comparison_text.configure(state='normal')
502
+ self.comparison_text.delete('1.0', 'end')
503
+ self.comparison_text.insert('1.0', report)
504
+ self.comparison_text.configure(state='disabled')
505
+
506
+ def get_values(self):
507
+ raw = self.input.get().strip()
508
+ # Accept either 3, 1, 2 or [3, 1, 2]; never eval the input.
509
+ values = ast.literal_eval(raw if raw.startswith('[') else '[' + raw + ']')
510
+ if not numeric_list(values):
511
+ raise ValueError('Enter up to 100 numbers between -1,000,000 and 1,000,000.')
512
+ return values
513
+
514
+ def start(self):
515
+ self.pause()
516
+ try:
517
+ values = self.get_values()
518
+ snapshots = [(p.source(), p.name.get().strip()) for p in self.panels]
519
+ for source, name in snapshots:
520
+ analyze(source, name)
521
+ except Exception as error:
522
+ messagebox.showerror('Check your input or Python code', str(error))
523
+ return
524
+ self.recorded_input = self.input.get()
525
+ self.snapshots = snapshots
526
+ self.tabs.select(self.animation_tab)
527
+ self.stop_jobs()
528
+ self.scratch = tempfile.TemporaryDirectory(prefix='sort_visualizer_')
529
+ self.bounds = (min([0] + values), max([0] + values))
530
+ for index, panel in enumerate(self.panels):
531
+ panel.reset(values)
532
+ panel.caption.set('Recording…')
533
+ # Lock the code so line highlighting matches the recorded version.
534
+ panel.editor.configure(state='disabled')
535
+ request = Path(self.scratch.name) / f'request_{index}.json'
536
+ response = Path(self.scratch.name) / f'response_{index}.json'
537
+ source, name = self.snapshots[index]
538
+ request.write_text(json.dumps({'source': source, 'name': name, 'values': values}), encoding='utf-8')
539
+ process = subprocess.Popen(
540
+ [sys.executable, str(Path(__file__).resolve()), '--worker', str(request), str(response)],
541
+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
542
+ self.jobs.append({'process': process, 'response': response, 'panel': panel,
543
+ 'started': time.monotonic()})
544
+ self.set_comparison('Comparing recorded code…')
545
+ request = Path(self.scratch.name) / 'comparison_request.json'
546
+ response = Path(self.scratch.name) / 'comparison_response.json'
547
+ request.write_text(json.dumps({'snapshots': snapshots, 'values': values}), encoding='utf-8')
548
+ process = subprocess.Popen(
549
+ [sys.executable, str(Path(__file__).resolve()), '--worker', str(request), str(response)],
550
+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
551
+ self.jobs.append({'process': process, 'response': response, 'panel': None,
552
+ 'started': time.monotonic()})
553
+ self.record_button.configure(state='disabled')
554
+ self.cancel_button.configure(state='normal')
555
+ self.status.set('Recording both functions… Each has an 8-second limit.')
556
+ self.root.after(80, self.poll)
557
+
558
+ def poll(self):
559
+ if not self.jobs:
560
+ return
561
+ for job in self.jobs:
562
+ if 'result' in job:
563
+ continue
564
+ process = job['process']
565
+ if process.poll() is None and time.monotonic() - job['started'] > TIMEOUT_SECONDS:
566
+ process.kill()
567
+ process.wait()
568
+ job['result'] = {'events': [], 'error': 'Timed out after 8 seconds. Check for an infinite loop.'}
569
+ elif process.poll() is not None:
570
+ try:
571
+ job['result'] = json.loads(job['response'].read_text(encoding='utf-8'))
572
+ except Exception:
573
+ job['result'] = {'events': [], 'error': 'The worker stopped without a readable result.'}
574
+ if not all('result' in job for job in self.jobs):
575
+ self.root.after(80, self.poll)
576
+ return
577
+ for job in self.jobs:
578
+ if job['panel'] is None:
579
+ self.set_comparison(job['result'].get('report') or job['result'].get('error', 'No report.'))
580
+ else:
581
+ job['panel'].result = job['result']
582
+ # Include intermediate values in the shared vertical scale.
583
+ all_values = [0] + [v for p in self.panels for e in p.result['events'] for v in e['values']]
584
+ self.bounds = (min(all_values), max(all_values))
585
+ self.refilter()
586
+ self.write_summary()
587
+ self.stop_jobs()
588
+ self.unlock()
589
+ self.status.set('Recording complete. Play or Step to inspect it. After editing code or input, record again.')
590
+
591
+ def unlock(self):
592
+ self.record_button.configure(state='normal')
593
+ self.cancel_button.configure(state='disabled')
594
+ for panel in self.panels:
595
+ panel.editor.configure(state='normal')
596
+
597
+ def write_summary(self):
598
+ lines = []
599
+ for label, panel in zip(('A', 'B'), self.panels):
600
+ result = panel.result
601
+ if result.get('error'):
602
+ lines.append(f"{label} ERROR:\n{result['error']}")
603
+ panel.caption.set('Recording error — see details below.')
604
+ else:
605
+ lines.append(f"{label}: {result['lines']} Python line events; "
606
+ f"{result['changes']} observed list changes; "
607
+ f"ascending result: {'YES' if result['sorted'] else 'NO'}; "
608
+ f"output: {result['output']}")
609
+ a, b = [p.result for p in self.panels]
610
+ if not a.get('error') and not b.get('error'):
611
+ lines.append('Same output on this input: ' + ('YES' if a['output'] == b['output'] else 'NO'))
612
+ if a.get('analysis') and b.get('analysis'):
613
+ differences = [f"{key}: A={a['analysis'][key]}, B={b['analysis'][key]}"
614
+ for key in a['analysis'] if a['analysis'][key] != b['analysis'][key]]
615
+ lines.extend(differences or ['The structural features checked are the same.'])
616
+ lines.append('Counts describe this recording, not runtime speed or Big-O complexity. '
617
+ 'Matching one input does not prove equivalence.')
618
+ self.summary.configure(state='normal')
619
+ self.summary.delete('1.0', 'end')
620
+ self.summary.insert('1.0', '\n'.join(lines))
621
+ self.summary.configure(state='disabled')
622
+
623
+ def refilter(self):
624
+ self.pause()
625
+ for panel in self.panels:
626
+ panel.set_filter(self.changes_only.get())
627
+
628
+ def sources_match(self):
629
+ return (self.recorded_input == self.input.get()
630
+ and self.snapshots == [(p.source(), p.name.get().strip()) for p in self.panels])
631
+
632
+ def advance(self):
633
+ if self.jobs or not self.sources_match():
634
+ self.status.set('Click Compare & Record to record the current code first.')
635
+ return False
636
+ advanced = False
637
+ for panel in self.panels:
638
+ if panel.position + 1 < len(panel.visible_events):
639
+ panel.show(panel.position + 1)
640
+ advanced = True
641
+ return advanced
642
+
643
+ def step_once(self):
644
+ self.pause()
645
+ self.advance()
646
+
647
+ def play(self):
648
+ if self.playing or self.jobs:
649
+ return
650
+ if not any(p.visible_events for p in self.panels):
651
+ self.status.set('Click Compare & Record first.')
652
+ return
653
+ self.tabs.select(self.animation_tab)
654
+ self.playing = True
655
+ self.tick()
656
+
657
+ def tick(self):
658
+ self.timer = None
659
+ if self.playing and self.advance():
660
+ self.timer = self.root.after(max(1, int(1000 / self.speed.get())), self.tick)
661
+ else:
662
+ self.playing = False
663
+
664
+ def pause(self):
665
+ self.playing = False
666
+ if self.timer is not None:
667
+ self.root.after_cancel(self.timer)
668
+ self.timer = None
669
+
670
+ def restart(self):
671
+ self.pause()
672
+ for panel in self.panels:
673
+ if panel.visible_events:
674
+ panel.show(0)
675
+
676
+ def show_diff(self):
677
+ self.pause()
678
+ self.diff_tab.refresh(*(panel.source() for panel in self.panels))
679
+ self.tabs.select(self.diff_tab)
680
+
681
+ def tab_changed(self, event):
682
+ # Clicking the tab itself also refreshes the current code comparison.
683
+ if self.tabs.select() == str(self.diff_tab):
684
+ self.pause()
685
+ self.diff_tab.refresh(*(panel.source() for panel in self.panels))
686
+
687
+ def stop_jobs(self):
688
+ for job in self.jobs:
689
+ if job['process'].poll() is None:
690
+ job['process'].kill()
691
+ job['process'].wait()
692
+ self.jobs = []
693
+ if self.scratch:
694
+ self.scratch.cleanup()
695
+ self.scratch = None
696
+
697
+ def cancel(self):
698
+ self.stop_jobs()
699
+ self.set_comparison('Comparison cancelled. Click Compare & Record to try again.')
700
+ self.unlock()
701
+ self.status.set('Recording cancelled. Edit the code and try again.')
702
+
703
+ def close(self):
704
+ self.pause()
705
+ self.stop_jobs()
706
+ self.root.destroy()
707
+
708
+ root = tk.Tk()
709
+ app = App(root)
710
+ root.mainloop()
711
+
712
+
713
+ if __name__ == '__main__':
714
+ if len(sys.argv) == 4 and sys.argv[1] == '--worker':
715
+ worker(sys.argv[2], sys.argv[3])
716
+ else:
717
+ launch_app()