-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathevaluate_from_apiX.py
More file actions
1667 lines (1459 loc) · 63.3 KB
/
evaluate_from_apiX.py
File metadata and controls
1667 lines (1459 loc) · 63.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import os
import json
import re
import time
import threading
import argparse
import sys
import select
import asyncio
try:
import termios
import tty
UNIX_TERMINAL = True
except ImportError:
UNIX_TERMINAL = False
termios = None
tty = None
from collections import deque
from openai import AsyncOpenAI
from datasets import load_dataset
import tiktoken
from rich.console import Console, Group
from rich.live import Live
from rich.text import Text
from rich.rule import Rule
from rich.panel import Panel
from rich.table import Table
from rich.layout import Layout
from rich.style import Style
from rich import box
# -------------------------------------------------------------------------
# Global Configuration & Patterns
# -------------------------------------------------------------------------
_PATTERNS = (r"answer is \(?([A-J])\)?", r"[aA]nswer:\s*([A-J])", r"\b[A-J]\b")
API_KEY = ""
args = None
GLOBAL_TOKENIZER = None
console = Console()
# -------------------------------------------------------------------------
# Global Data Buffers (decoupled architecture)
# QUESTION_RUNNERS write to these, RENDERER reads from them
# -------------------------------------------------------------------------
QUESTION_STATE_BUFFER = {}
LOG_MESSAGES = []
LOG_LOCK = threading.Lock()
STATE_LOCK = threading.Lock()
RENDERING_ACTIVE = True
# -------------------------------------------------------------------------
# Buffer Access Functions (for question runners)
# -------------------------------------------------------------------------
def buffer_log(message):
timestamp = time.strftime("%H:%M:%S")
with LOG_LOCK:
LOG_MESSAGES.append(f"[{timestamp}] {message}")
if len(LOG_MESSAGES) > 50:
LOG_MESSAGES.pop(0)
def buffer_update_question(q_num, **kwargs):
with STATE_LOCK:
if q_num not in QUESTION_STATE_BUFFER:
QUESTION_STATE_BUFFER[q_num] = {
"status": "pending",
"tokens": 0,
"rate": 0.0,
"elapsed": 0,
"stalled": False,
"retry_count": 0,
}
QUESTION_STATE_BUFFER[q_num].update(kwargs)
def buffer_set_question_status(q_num, status):
with STATE_LOCK:
if q_num not in QUESTION_STATE_BUFFER:
QUESTION_STATE_BUFFER[q_num] = {}
QUESTION_STATE_BUFFER[q_num]["status"] = status
def buffer_get_state_snapshot():
with STATE_LOCK:
return dict(QUESTION_STATE_BUFFER)
def buffer_get_log_snapshot():
with LOG_LOCK:
return list(LOG_MESSAGES)
def buffer_clear():
global QUESTION_STATE_BUFFER, LOG_MESSAGES
with STATE_LOCK:
QUESTION_STATE_BUFFER.clear()
with LOG_LOCK:
LOG_MESSAGES.clear()
# Braille spinner frames (feature 9)
SPINNER_FRAMES = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
# FIX 2/3: Rolling window duration for tok/s calculation (seconds)
_RATE_WINDOW_SECS = 8.0
# FIX 4: Seconds without a token update before a question is considered stalled
_STALL_THRESHOLD_SECS = 25.0
def get_tokenizer():
global GLOBAL_TOKENIZER
if GLOBAL_TOKENIZER is None:
GLOBAL_TOKENIZER = tiktoken.get_encoding("cl100k_base")
return GLOBAL_TOKENIZER
# -------------------------------------------------------------------------
# File Lock & Shared State
# -------------------------------------------------------------------------
file_lock = threading.Lock()
GLOBAL_QUIT_REQUESTED = False
SCROLL_OFFSET = 0
INPUT_PROMPT_ACTIVE = False
AUTO_SCROLL = True # auto-follow active questions; disabled on manual scroll
# -------------------------------------------------------------------------
# API Client
# -------------------------------------------------------------------------
def get_async_client():
return AsyncOpenAI(api_key=API_KEY, base_url=args.url, timeout=3600.0)
# -------------------------------------------------------------------------
# Data Loading & Preprocessing
# -------------------------------------------------------------------------
def load_mmlu_pro():
dataset = load_dataset("TIGER-Lab/MMLU-Pro")
test_df, val_df = dataset["test"], dataset["validation"]
return preprocess(test_df), preprocess(val_df)
def preprocess(raw):
cleaned = []
for each in raw:
opts = [opt for opt in each["options"] if opt != "N/A"]
each["options"] = opts
cleaned.append(each)
grouped = {}
for each in cleaned:
grouped.setdefault(each["category"], []).append(each)
return grouped
def format_example(question, options, cot_content=""):
if not cot_content:
cot_content = "Let's think step by step."
if cot_content.startswith("A: "):
cot_content = cot_content[3:]
example = f"Question: {question}\nOptions: "
choice_map = "ABCDEFGHIJ"
for i, opt in enumerate(options):
example += f"{choice_map[i]}. {opt}\n"
if cot_content:
example += f"Answer: {cot_content}\n\n"
else:
example += "Answer: "
return example
def extract_answer(text):
for pattern in _PATTERNS:
if matches := re.findall(pattern, text):
return matches[-1]
return None
# -------------------------------------------------------------------------
# Exceptions
# -------------------------------------------------------------------------
class MaxTokensExceeded(Exception):
pass
class MissingUsageError(Exception):
pass
# -------------------------------------------------------------------------
# Active Question Tracker (Display & State)
# -------------------------------------------------------------------------
class ActiveQuestionTracker:
def __init__(self, subject, total_questions, max_concurrent=4, loop=None):
self.subject = subject
self.total_questions = total_questions
self.max_concurrent = max_concurrent
self.completed = 0
self.start_time = time.time()
self.loop = loop
self.active_questions = {} # q_num -> (task, start_time, stop_event, restart, kill, retry_count)
self.token_counts = {}
# FIX 2: Replace single last_token_time + EMA rate with a rolling-window deque per question.
# Each deque holds (timestamp, cumulative_token_count) samples.
self.token_history = {} # q_num -> deque of (ts, cum_tokens)
self.token_rates = {} # q_num -> computed tok/s (float)
self.stalled = {}
self.lock = threading.Lock()
self.keyboard_listener_active = True
# Wall State
self.question_results = {}
self.log_messages = []
self.last_render_time = 0
self.render_interval = (
1.0 # Reduced to 1 second to avoid interfering with input
)
# Cache terminal size
self.last_cols = 0
self.last_rows = 0
# Rich Live reference (set externally before first render)
self.live = None
# Animation state (features 9, 10)
self._spinner_idx = 0
self._stall_pulse = False # flips each render tick
self.log(f"Starting {subject} ({total_questions} questions)")
self.log(
f"Controls: [Up/Down] Scroll (disables auto-scroll) | [r] restart | [k] kill | [q] quit"
)
if args.retry > 0:
self.log(f"Max token retries: {args.retry}")
# -----------------------------------------------------------------------
# State Mutators
# -----------------------------------------------------------------------
def log(self, message):
timestamp = time.strftime("%H:%M:%S")
self.log_messages.append(f"[{timestamp}] {message}")
if len(self.log_messages) > 50:
self.log_messages.pop(0)
buffer_log(message)
def start_question(self, question_num, task, stop_event):
with self.lock:
self.active_questions[question_num] = (
task,
time.time(),
stop_event,
False,
False,
0,
)
self.token_counts[question_num] = 0
self.token_history[question_num] = deque()
self.token_rates[question_num] = 0.0
self.stalled[question_num] = False
self.question_results[question_num] = "active"
buffer_update_question(
question_num,
status="active",
tokens=0,
rate=0.0,
stalled=False,
start_time=time.time(),
)
# FIX 2 & 3: `count_only` parameter prevents rate recalculation on the final
# usage_data flush (which would cause a spike: large token jump, near-zero dt).
# FIX 5: Resetting to 0 now also clears the history deque and rate.
def update_token(self, question_num, token_count, count_only=False):
rate = 0.0
with self.lock:
if question_num not in self.token_counts:
return
now = time.time()
if count_only or token_count == 0:
self.token_counts[question_num] = token_count
if token_count == 0:
self.token_history[question_num] = deque()
self.token_rates[question_num] = 0.0
self.stalled[question_num] = False
rate = self.token_rates.get(question_num, 0.0)
buffer_update_question(
question_num, tokens=token_count, rate=rate, stalled=False
)
return
self.token_counts[question_num] = token_count
hist = self.token_history[question_num]
hist.append((now, token_count))
cutoff = now - _RATE_WINDOW_SECS
while hist and hist[0][0] < cutoff:
hist.popleft()
if len(hist) >= 2:
dt = hist[-1][0] - hist[0][0]
delta = hist[-1][1] - hist[0][1]
if dt > 0.05 and delta > 0:
self.token_rates[question_num] = delta / dt
rate = self.token_rates.get(question_num, 0.0)
self.stalled[question_num] = False
buffer_update_question(
question_num, tokens=token_count, rate=rate, stalled=False
)
def set_stalled(self, question_num, stalled):
with self.lock:
if question_num in self.stalled:
self.stalled[question_num] = stalled
buffer_update_question(question_num, stalled=stalled)
def complete_question(self, question_num, token_count=None, success=True):
with self.lock:
if question_num in self.active_questions:
del self.active_questions[question_num]
self.token_counts.pop(question_num, None)
self.token_history.pop(question_num, None)
self.token_rates.pop(question_num, None)
self.stalled.pop(question_num, None)
status = "success" if success else "wrong"
self.question_results[question_num] = status
if success:
self.completed += 1
buffer_set_question_status(question_num, status)
if success:
self.log(f"Q{question_num} completed ({token_count} tokens)")
else:
self.log(f"Q{question_num} failed/wrong answer")
def kill_question(self, question_num):
with self.lock:
if question_num in self.active_questions:
task, start_time, stop_event, _, _, retry_count = self.active_questions[
question_num
]
self.active_questions[question_num] = (
task,
start_time,
stop_event,
False,
True,
retry_count,
)
if stop_event:
stop_event.set()
self.log(f"Q{question_num} marked for kill")
return True
else:
self.log(f"Q{question_num} is not active")
return False
def restart_question(self, question_num):
with self.lock:
if question_num in self.active_questions:
task, start_time, stop_event, _, _, retry_count = self.active_questions[
question_num
]
self.active_questions[question_num] = (
task,
start_time,
stop_event,
True,
False,
retry_count,
)
if stop_event:
stop_event.set()
self.log(f"Q{question_num} marked for restart")
return True
else:
self.log(f"Q{question_num} is not active")
return False
def increment_retry_count(self, question_num):
with self.lock:
if question_num in self.active_questions:
task, start_time, stop_event, restart_flag, kill_flag, retry_count = (
self.active_questions[question_num]
)
retry_count += 1
self.active_questions[question_num] = (
task,
start_time,
stop_event,
restart_flag,
kill_flag,
retry_count,
)
return retry_count
return 0
def get_retry_count(self, question_num):
with self.lock:
if question_num in self.active_questions:
_, _, _, _, _, retry_count = self.active_questions[question_num]
return retry_count
return 0
def get_flags(self, question_num):
with self.lock:
if question_num in self.active_questions:
_, _, _, restart_flag, kill_flag, _ = self.active_questions[
question_num
]
return restart_flag, kill_flag
return False, False
def clear_flags(self, question_num):
with self.lock:
if question_num in self.active_questions:
task, start_time, stop_event, _, _, retry_count = self.active_questions[
question_num
]
self.active_questions[question_num] = (
task,
start_time,
stop_event,
False,
False,
retry_count,
)
def stop_all_questions(self):
with self.lock:
for question_num, (task, start_time, stop_event, _, _, _) in list(
self.active_questions.items()
):
if stop_event:
stop_event.set()
if task and not task.done() and self.loop:
self.loop.call_soon_threadsafe(task.cancel)
self.token_counts.pop(question_num, None)
self.token_history.pop(question_num, None)
self.token_rates.pop(question_num, None)
self.stalled.pop(question_num, None)
self.active_questions.clear()
self.keyboard_listener_active = False
buffer_clear()
def any_stalled(self):
with self.lock:
return any(self.stalled.values())
def calculate_accuracy(self):
finished = [
v for v in self.question_results.values() if v in ("success", "wrong")
]
total = len(finished)
if total == 0:
return 0.0
return sum(1 for v in finished if v == "success") / total * 100
# -----------------------------------------------------------------------
# Feature 8: age-based colour for active question cells
# -----------------------------------------------------------------------
def _age_style(self, elapsed_secs: float) -> str:
if elapsed_secs < 30:
return "white"
elif elapsed_secs < 90:
return "yellow"
elif elapsed_secs < 180:
return "color(208)" # orange
else:
return "red"
# -----------------------------------------------------------------------
# FIX 4: Stall detection — called once per render tick so no extra thread needed.
# -----------------------------------------------------------------------
def _check_stalls(self, now: float):
"""Mark questions stalled if their token history hasn't advanced recently."""
with self.lock:
for q_num, hist in self.token_history.items():
if not hist:
# No samples yet (just started) — not stalled
continue
last_ts = hist[-1][0]
if now - last_ts > _STALL_THRESHOLD_SECS:
self.stalled[q_num] = True
# -----------------------------------------------------------------------
# Rich Rendering
# Feature 1 : two-column Layout (grid left, detail+log right)
# Feature 2 : active-questions detail Table (right-top panel)
# Feature 3 : subject header wrapped in a Panel with border title
# Features 8,9,10 applied inside the grid and the detail table
# -----------------------------------------------------------------------
def get_renderable(self):
now = time.time()
# FIX 4: Detect stalls on every render tick (cheap, lock-free from caller's pov)
self._check_stalls(now)
try:
term_size = os.get_terminal_size()
cols = term_size.columns
rows = term_size.lines
self.last_cols, self.last_rows = cols, rows
except OSError:
cols = self.last_cols or 80
rows = self.last_rows or 24
# Advance animation state once per render tick
self._spinner_idx += 1
self._stall_pulse = not self._stall_pulse
spinner_char = SPINNER_FRAMES[self._spinner_idx % len(SPINNER_FRAMES)]
# Thread-safe snapshot - read from global buffer
q_results = dict(self.question_results)
active_qs = dict(self.active_questions)
# Read active question state from global buffer
buffer_state = buffer_get_state_snapshot()
tok_counts = {q: s.get("tokens", 0) for q, s in buffer_state.items()}
tok_rates = {q: s.get("rate", 0.0) for q, s in buffer_state.items()}
stalled = {q: s.get("stalled", False) for q, s in buffer_state.items()}
log_msgs = buffer_get_log_snapshot()
correct = sum(1 for v in q_results.values() if v == "success")
wrong_count = sum(1 for v in q_results.values() if v == "wrong")
acc = self.calculate_accuracy()
elapsed = int(now - self.start_time)
total_rate = sum(tok_rates.values())
total_toks = sum(tok_counts.values())
# ----------------------------------------------------------------
# Feature 3: Header Panel
# ----------------------------------------------------------------
hdr = Text(justify="left")
hdr.append("Progress ", style="dim")
hdr.append(f"{correct}", style="bold green")
hdr.append(f"/{self.total_questions} ", style="dim")
hdr.append("Acc ", style="dim")
hdr.append(f"{acc:.1f}% ", style="bold yellow")
hdr.append("Wrong ", style="dim")
hdr.append(f"{wrong_count} ", style="bold color(208)")
hdr.append("Elapsed ", style="dim")
hdr.append(f"{elapsed}s ", style="dim")
hdr.append("Tokens ", style="dim")
hdr.append(f"{total_toks:,} ", style="bold magenta")
hdr.append("∑tok/s ", style="dim")
hdr.append(f"{total_rate:.0f}", style="bold cyan")
header_panel = Panel(
hdr,
title=f"[bold white]MMLU-Pro[/bold white] [bold cyan]{self.subject}[/bold cyan]",
border_style="cyan",
padding=(0, 1),
)
# ----------------------------------------------------------------
# Feature 2: Active Questions Detail Table (right-top)
# ----------------------------------------------------------------
active_table = Table(
show_header=True,
header_style="bold dim",
box=box.SIMPLE,
expand=True,
show_edge=False,
padding=(0, 1),
)
active_table.add_column("Q#", width=6, no_wrap=True)
active_table.add_column("Time", width=6, no_wrap=True)
active_table.add_column("Tokens", width=7, no_wrap=True)
active_table.add_column("Tok/s", width=6, no_wrap=True)
active_table.add_column("Retry", width=5, no_wrap=True)
active_table.add_column("", width=2, no_wrap=True) # spinner / stall indicator
for q_num in sorted(active_qs.keys()):
_, q_start, _, _, _, retry_cnt = active_qs[q_num]
q_elapsed = now - q_start
tokens = tok_counts.get(q_num, 0)
rate = tok_rates.get(q_num, 0.0)
is_stalled = stalled.get(q_num, False)
age_sty = self._age_style(q_elapsed)
if is_stalled:
# Feature 10: pulse row style between bold-red and dim-red
row_style = (
Style(bold=True, color="red")
if self._stall_pulse
else Style(color="dark_red")
)
indicator = Text("!", style="bold red")
else:
row_style = Style(color=age_sty)
indicator = Text(spinner_char, style="green") # Feature 9
active_table.add_row(
f"Q{q_num}",
f"{int(q_elapsed)}s",
str(tokens),
f"{rate:.0f}" if rate > 0 else "—",
str(retry_cnt) if retry_cnt > 0 else "—",
indicator,
style=row_style,
)
active_panel = Panel(
active_table,
title="[bold white]Active Questions[/bold white]",
border_style="blue",
padding=(0, 0),
)
# ----------------------------------------------------------------
# Log panel (right-bottom)
# ----------------------------------------------------------------
log_text = Text()
log_height = 10
for msg in log_msgs[max(0, len(log_msgs) - log_height) :]:
clean = "".join(c for c in msg if c.isprintable())
log_text.append(clean + "\n", style="dim")
log_panel = Panel(
log_text,
title="[bold white]Messages[/bold white]",
border_style="blue",
padding=(0, 1),
)
# ----------------------------------------------------------------
# Question Grid (left panel)
# Features 8 (age color), 9 (spinner), 10 (stall pulse) on cells
# ----------------------------------------------------------------
# Estimate inner width of the left (~3/4) panel
left_inner_w = max(10, (cols * 3 // 4) - 4)
block_w = 7 # chars per grid cell: [###]xx (no symbols, tight)
grid_cols = max(1, left_inner_w // block_w)
# rows used: header(3) + footer(1) + grid-panel borders(2) = 6
content_height = max(1, rows - 6)
total_rows = (self.total_questions + grid_cols - 1) // grid_cols
global SCROLL_OFFSET, AUTO_SCROLL
max_scroll = max(0, total_rows - content_height)
SCROLL_OFFSET = max(0, min(SCROLL_OFFSET, max_scroll))
# Auto-scroll: keep lowest active question row in view
if AUTO_SCROLL and active_qs:
lowest_active_row = max((q_num - 1) // grid_cols for q_num in active_qs)
visible_end = SCROLL_OFFSET + content_height - 1
if lowest_active_row > visible_end:
SCROLL_OFFSET = min(max_scroll, lowest_active_row - content_height + 1)
elif lowest_active_row < SCROLL_OFFSET:
SCROLL_OFFSET = lowest_active_row
start_idx = SCROLL_OFFSET * grid_cols
end_idx = min(self.total_questions, start_idx + content_height * grid_cols)
grid_text = Text()
current_row_items = []
for q_idx in range(start_idx, end_idx):
q_num = q_idx + 1
status = q_results.get(q_num, "pending")
is_active = q_num in active_qs
item = Text(no_wrap=True)
if is_active:
_, q_start, _, _, _, retry_cnt = active_qs[q_num]
q_elapsed = now - q_start
tokens = tok_counts.get(q_num, 0)
is_stalled = stalled.get(q_num, False)
age_sty = self._age_style(q_elapsed) # Feature 8
if is_stalled:
# Feature 10: alternate between bg highlight and plain red
if self._stall_pulse:
item.append(
f"{q_num:03d}",
style=Style(bold=True, color="white", bgcolor="red"),
)
item.append(
"!", style=Style(bold=True, color="white", bgcolor="red")
)
else:
item.append(f"{q_num:03d}", style=Style(bold=True, color="red"))
item.append("!", style=Style(bold=True, color="red"))
else:
# q_num fixed white, spinner right of it, then token count age-colored
if tokens >= 10000:
tok_str = f"{tokens // 1000}"
elif tokens >= 1000:
tok_str = f"{tokens // 1000} "
else:
tok_str = f"{tokens:<3}"
item.append(f"{q_num:03d}", style="white")
item.append(spinner_char, style="green")
item.append(tok_str[:3], style=age_sty)
elif status == "success":
item.append(f"{q_num:03d}", style="green")
elif status == "wrong":
item.append(f"{q_num:03d}", style="bold color(208)")
else:
item.append(f"{q_num:03d}", style="bright_black")
# Pad to fixed cell width
pad = block_w - len(item.plain)
if pad > 0:
item.append(" " * pad)
current_row_items.append(item)
if len(current_row_items) == grid_cols:
for it in current_row_items:
grid_text.append_text(it)
grid_text.append("\n")
current_row_items = []
if current_row_items:
for it in current_row_items:
grid_text.append_text(it)
grid_text.append("\n")
if total_rows > content_height:
auto_tag = "[auto]" if AUTO_SCROLL else "[manual - ↑↓ or 'a' to re-enable]"
grid_text.append(
f"── Scroll {SCROLL_OFFSET}/{max_scroll} (↑/↓) {auto_tag} ──",
style="bright_black",
)
grid_panel = Panel(
grid_text,
title="[bold white]Question Wall[/bold white]",
border_style="bright_black",
padding=(0, 1),
)
# ----------------------------------------------------------------
# Footer controls bar (one line, no panel)
# ----------------------------------------------------------------
controls = Text(justify="center")
controls.append(" [r] ", style="bold yellow")
controls.append("restart ", style="dim")
controls.append("[k] ", style="bold red")
controls.append("kill ", style="dim")
controls.append("[↑↓] ", style="bold white")
controls.append("scroll ", style="dim")
controls.append("[a] ", style="bold cyan")
auto_lbl = "auto-scroll ON " if AUTO_SCROLL else "auto-scroll OFF"
controls.append(auto_lbl + " ", style="bold cyan" if AUTO_SCROLL else "dim")
controls.append("[q] ", style="bold magenta")
controls.append("quit ", style="dim")
controls.append(
f"│ active {len(active_qs)}/{self.max_concurrent}", style="dim"
)
# ----------------------------------------------------------------
# Feature 1: Two-column Layout assembly
# ----------------------------------------------------------------
layout = Layout()
layout.split_column(
Layout(header_panel, name="header", size=3),
Layout(name="body"),
Layout(controls, name="footer", size=1),
)
layout["body"].split_row(
Layout(grid_panel, name="left", ratio=3),
Layout(name="right", ratio=1),
)
layout["right"].split_column(
Layout(active_panel, name="active", ratio=1),
Layout(log_panel, name="log", ratio=1),
)
return layout
def render_screen(self):
"""Throttled update of the Rich Live display."""
global RENDERING_ACTIVE
now = time.time()
if not RENDERING_ACTIVE:
return
if now - self.last_render_time < self.render_interval:
return
self.last_render_time = now
if self.live is not None:
try:
self.live.update(self.get_renderable(), refresh=True)
except Exception:
pass
# -------------------------------------------------------------------------
# Keyboard Listener
# FIX: SSH-compatible terminal handling - avoid switching between cbreak/canonical modes
# -------------------------------------------------------------------------
def keyboard_listener(tracker, event_loop):
global \
GLOBAL_QUIT_REQUESTED, \
SCROLL_OFFSET, \
INPUT_PROMPT_ACTIVE, \
AUTO_SCROLL, \
RENDERING_ACTIVE
if not UNIX_TERMINAL:
console.print(
"\n[yellow]Terminal input not available on this platform - running in non-interactive mode[/yellow]"
)
console.print(
"[dim]Note: Keyboard controls (r, k, q, arrow keys) are disabled.[/dim]"
)
while tracker.keyboard_listener_active and not GLOBAL_QUIT_REQUESTED:
time.sleep(1)
return
fd = sys.stdin.fileno()
try:
old_settings = termios.tcgetattr(fd)
except termios.error:
console.print(
"\n[red]Terminal not available - running in non-interactive mode[/red]"
)
return
input_buffer = []
input_mode_active = False
def read_key_nonblocking():
"""Read a single keypress, handling escape sequences for arrow keys."""
try:
if not select.select([fd], [], [], 0.01)[0]:
return None
raw = os.read(fd, 1)
if not raw:
return None
key = raw.decode("utf-8", errors="ignore")
if key == "\x1b":
seq = ""
for _ in range(4):
if select.select([fd], [], [], 0.05)[0]:
seq += os.read(fd, 1).decode("utf-8", errors="ignore")
else:
break
if "[A" in seq:
return "UP"
elif "[B" in seq:
return "DOWN"
return "ESC"
return key
except Exception:
return None
def drain_input():
"""Clear any pending input from the buffer."""
try:
termios.tcflush(fd, termios.TCIFLUSH)
except Exception:
pass
def restore_terminal_and_get_input(prompt_text):
"""Temporarily restore canonical mode for safe input over SSH."""
global RENDERING_ACTIVE
nonlocal input_mode_active
RENDERING_ACTIVE = False
try:
termios.tcsetattr(fd, termios.TCSANOW, old_settings)
except Exception:
pass
input_mode_active = False
try:
drain_input()
sys.stdout.write("\r\n")
sys.stdout.flush()
result = input(prompt_text)
sys.stdout.write("\r")
sys.stdout.flush()
return result
finally:
try:
tty.setcbreak(fd)
termios.tcflush(fd, termios.TCIFLUSH)
input_mode_active = True
RENDERING_ACTIVE = True
except Exception:
pass
try:
tty.setcbreak(fd)
termios.tcflush(fd, termios.TCIFLUSH)
tracker.log("Keyboard listener started (SSH-compatible mode).")
while tracker.keyboard_listener_active and not GLOBAL_QUIT_REQUESTED:
try:
key = read_key_nonblocking()
if key is None:
time.sleep(0.005)
continue
if key == "UP":
AUTO_SCROLL = False
SCROLL_OFFSET = max(0, SCROLL_OFFSET - 1)
continue
if key == "DOWN":
AUTO_SCROLL = False
SCROLL_OFFSET += 1
continue
if key.lower() == "a":
AUTO_SCROLL = True
tracker.log("Auto-scroll re-enabled")
continue
if key.lower() == "q":
INPUT_PROMPT_ACTIVE = True
live = tracker.live
if live is not None:
live.stop()
confirm = restore_terminal_and_get_input("Quit? (y/N): ")
confirm = (confirm or "").strip().lower()
if confirm == "y":
tracker.log("Quit requested.")
GLOBAL_QUIT_REQUESTED = True
tracker.stop_all_questions()
return
if live is not None:
live.start()
INPUT_PROMPT_ACTIVE = False
continue
if key.lower() in ["r", "k"]:
INPUT_PROMPT_ACTIVE = True
with tracker.lock:
active_snap = dict(tracker.active_questions)
tok_snap = dict(tracker.token_counts)
rate_snap = dict(tracker.token_rates)
stalled_snap = dict(tracker.stalled)
if not active_snap:
tracker.log("No active questions")
time.sleep(1)
INPUT_PROMPT_ACTIVE = False
continue
live = tracker.live
if live is not None:
live.stop()
action = "restart" if key.lower() == "r" else "kill"
action_color = "yellow" if action == "restart" else "red"
pick_table = Table(
title=f"[bold {action_color}]Select question to {action}[/bold {action_color}]",
box=box.ROUNDED,
border_style=action_color,
header_style=f"bold {action_color}",
show_lines=False,
expand=False,
)
pick_table.add_column("Q#", width=6, no_wrap=True)
pick_table.add_column("Elapsed", width=8, no_wrap=True)
pick_table.add_column("Tokens", width=8, no_wrap=True)
pick_table.add_column("Tok/s", width=8, no_wrap=True)
pick_table.add_column("Retries", width=7, no_wrap=True)
pick_table.add_column("State", width=10, no_wrap=True)
now = time.time()
for q_num in sorted(active_snap.keys()):
_, q_start, _, _, _, retry_cnt = active_snap[q_num]
q_elapsed = now - q_start
tokens = tok_snap.get(q_num, 0)
rate = rate_snap.get(q_num, 0.0)
is_stalled = stalled_snap.get(q_num, False)
state_txt = (
Text("STALLED", style="bold red")
if is_stalled
else Text("active", style="green")
)
if q_elapsed < 30:
row_sty = "white"
elif q_elapsed < 90: