File size: 10,320 Bytes
b4396f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Dashboard eval-progress patch (Young's request 2026-11-20 15:01):
add a self-discovering "Tien do eval" section to the sera-v4 dashboard
(~/sera_v4_dashboard/server.py).

- eval_progress() scans every *.jsonl eval result in the result dirs
  the dashboard knows (fewshot/results, frontend_probe/results,
  round2_probe/results, measurement/results) on each collect() call,
  so future eval tasks appear automatically with no code change.
- Per file: episodes = parsed JSONL rows, success = rows with truthy
  "success", expected total inferred from the companion .log first,
  then from protocol name patterns (cond/e3 -> 180, z -> 60,
  o2ctrl -> 30, probe dirs/horizon/oracle -> 70), else null
  ("chua ro tong" -- never fabricate a denominator).
- Status: RUNNING when a live eval process writes that exact file
  (--out in cmdline, or an open fd in /proc, or mtime < 180s),
  DONE when rows >= expected, PARTIAL when short with no writer,
  UNKNOWN when the total cannot be inferred.
- Smoke/trace files are skipped, same convention as probe_files().
Every replacement is exact-match asserted. Backup: server.py.bak-eval-20261120.
"""
import shutil
from pathlib import Path

P = Path.home() / "sera_v4_dashboard" / "server.py"
src = P.read_text()
orig = src

EVAL_FUNCS = '''
def _eval_expected_total(fn, dirkey, path):
    """Suy tong episode ky vong cua mot file eval: log di kem truoc, mau ten
    file theo giao thuc sau. Khong suy ra duoc -> None (hien 'chua ro tong')."""
    logp = path[:-len(".jsonl")] + ".log"
    try:
        text = _read_tail(logp, 131072)
        for pat in (r"episodes?\\s*[:=]\\s*(\\d{2,4})",
                    r"total[ _]?episodes?\\s*[:=]\\s*(\\d{2,4})",
                    r"\\b(\\d{2,4})\\s+episodes?\\b"):
            v = _last_float(pat, text)
            if v:
                return int(v)
    except Exception:
        pass
    low = fn.lower()
    if "o2ctrl" in low:
        return 30
    if "cond" in low or "-e3-" in low:
        return 180
    if "comp-z" in low or re.search(r"(^|[-_])z([-_.]|$)", low):
        return 60
    if dirkey in ("frontend_probe", "round2_probe") or "probe" in low \\
            or "horizon" in low or "oracle" in low:
        return 70
    return None


def _eval_active_files():
    """Tap path .jsonl dang duoc tien trinh eval ghi: --out trong cmdline
    hoac fd dang mo cua tien trinh eval (loai tru chinh dashboard)."""
    active = set()
    try:
        r = subprocess.run(["pgrep", "-af", "python"],
                           capture_output=True, text=True, timeout=6)
        for line in r.stdout.splitlines():
            if "eval" not in line:
                continue
            m = re.search(r"--out[= ](\\S+\\.jsonl)", line)
            if m:
                active.add(os.path.abspath(m.group(1)))
    except Exception:
        pass
    me = str(os.getpid())
    try:
        for pid in os.listdir("/proc"):
            if not pid.isdigit() or pid == me:
                continue
            try:
                with open(os.path.join("/proc", pid, "cmdline"), "rb") as f:
                    cmd = f.read().decode("utf-8", errors="ignore")
            except Exception:
                continue
            if "eval" not in cmd:
                continue
            fdd = os.path.join("/proc", pid, "fd")
            try:
                fds = os.listdir(fdd)
            except Exception:
                continue
            for fd in fds:
                try:
                    t = os.readlink(os.path.join(fdd, fd))
                except Exception:
                    continue
                if t.endswith(".jsonl"):
                    active.add(t)
    except Exception:
        pass
    return active


def _age_text(age):
    if age is None:
        return None
    if age < 90:
        return "vua xong"
    if age < 3600:
        return "%d phut truoc" % int(age // 60)
    if age < 86400:
        return "%d gio truoc" % int(age // 3600)
    return "%d ngay truoc" % int(age // 86400)


def eval_progress():
    """Tu phat hien moi file .jsonl ket qua eval trong cac thu muc ket qua
    da biet; doc tuoi moi lan collect() nen eval moi tu hien."""
    active = _eval_active_files()
    now = time.time()
    rows = []
    for dirkey, folder in EVAL_DIRS:
        try:
            files = sorted(os.listdir(folder))
        except Exception:
            continue
        for fn in files:
            if not fn.endswith(".jsonl") or ".trace" in fn or "smoke" in fn:
                continue
            path = os.path.join(folder, fn)
            n = succ = 0
            try:
                with open(path, errors="ignore") as f:
                    for line in f:
                        line = line.strip()
                        if not line:
                            continue
                        try:
                            r = json.loads(line)
                        except Exception:
                            continue
                        n += 1
                        if r.get("success"):
                            succ += 1
            except Exception:
                continue
            try:
                age = now - os.path.getmtime(path)
            except Exception:
                age = None
            expected = _eval_expected_total(fn, dirkey, path)
            running = os.path.abspath(path) in active or \\
                (age is not None and age < 180)
            if running:
                status = "RUNNING"
            elif expected is not None and n >= expected:
                status = "DONE"
            elif expected is not None:
                status = "PARTIAL"
            else:
                status = "UNKNOWN"
            rows.append({
                "name": fn[:-len(".jsonl")],
                "file": fn,
                "dir": dirkey,
                "episodes": n,
                "expected": expected,
                "pct": round(100.0 * n / expected, 1) if expected else None,
                "success": succ,
                "success_rate": round(100.0 * succ / n, 1) if n else None,
                "status": status,
                "age_s": round(age) if age is not None else None,
                "age_text": _age_text(age),
            })
    rank = {"RUNNING": 0, "PARTIAL": 1, "UNKNOWN": 2, "DONE": 3}
    rows.sort(key=lambda r: (rank.get(r["status"], 9),
                             r["age_s"] if r["age_s"] is not None else 10 ** 12))
    return rows


'''

EVAL_RENDER = '''  if(d.eval_progress&&d.eval_progress.length){
    let s="<table><tr><th>Eval</th><th>Thư mục</th><th>Episode</th><th>% xong</th><th>Thành công</th><th>Trạng thái</th><th>Cập nhật</th></tr>";
    for(const e of d.eval_progress){
      const tot=e.expected?e.episodes+"/"+e.expected:e.episodes+" / chưa rõ tổng";
      s+=`<tr><td><b>${e.name}</b></td><td>${e.dir}</td><td>${tot}</td><td>${e.pct===null?"—":e.pct+"%"}</td><td>${e.success} (${e.success_rate===null?"—":e.success_rate+"%"})</td><td style="text-align:left">${ebadge(e.status)}</td><td>${e.age_text||"—"}</td></tr>`;
    }
    $("evals").innerHTML=s+"</table>";
  } else $("evals").innerHTML="<span class='mut'>—</span>";
'''

REPLACEMENTS = []

# 1. FS_RES + EVAL_DIRS constants after FE_RES
REPLACEMENTS.append((
    'FE_RES = os.path.join(EXP, "frontend_probe", "results")\n',
    'FE_RES = os.path.join(EXP, "frontend_probe", "results")\n'
    'FS_RES = os.path.join(EXP, "fewshot", "results")\n'
    'EVAL_DIRS = [("fewshot", FS_RES), ("frontend_probe", FE_RES),\n'
    '             ("round2_probe", R2_RES), ("measurement", MEAS_DIR)]\n',
))

# 2. eval functions before collect()
REPLACEMENTS.append((
    "def collect():\n",
    EVAL_FUNCS + "def collect():\n",
))

# 3. collect(): add eval_progress payload
REPLACEMENTS.append((
    '        "ledger": VERDICT_LEDGER,\n',
    '        "ledger": VERDICT_LEDGER,\n'
    '        "eval_progress": eval_progress(),\n',
))

# 4. CSS: partial / unknown badges
REPLACEMENTS.append((
    ".badge.fail{background:var(--red)} .badge.pass{background:var(--green)} .badge.stopped{background:#5a6b7a} .badge.cancel{background:#8a97a5}",
    ".badge.fail{background:var(--red)} .badge.pass{background:var(--green)} .badge.stopped{background:#5a6b7a} .badge.cancel{background:#8a97a5}\n"
    "  .badge.part{background:var(--orange)} .badge.unk{background:#8a97a5}",
))

# 5. HTML: eval section before the verdict ledger section
REPLACEMENTS.append((
    '  <section><h2>Tổng kết verdict toàn chương trình</h2><div id="ledger"></div>\n',
    '  <section><h2>Tiến độ eval</h2><div id="evals"></div>\n'
    '    <p class="mut" style="font-size:12px;margin:8px 0 0">Tự động quét mọi file .jsonl kết quả eval trong fewshot/results, frontend_probe/results, round2_probe/results, measurement/results — task eval mới tự hiện ở lần tải kế tiếp, không cần sửa dashboard. RUNNING = có tiến trình eval đang ghi vào đúng file đó; DONE = đủ số episode kỳ vọng; PARTIAL = thiếu episode và không còn tiến trình ghi; tổng kỳ vọng suy từ log đi kèm hoặc giao thức theo tên file, không suy ra được thì ghi "chưa rõ tổng".</p></section>\n'
    '  <section><h2>Tổng kết verdict toàn chương trình</h2><div id="ledger"></div>\n',
))

# 6. JS: ebadge helper after vbadge
REPLACEMENTS.append((
    'function vbadge(s){return s?`<span class="badge ${vcls(s)}">${s}</span>`:"—"}\n',
    'function vbadge(s){return s?`<span class="badge ${vcls(s)}">${s}</span>`:"—"}\n'
    'function ebadge(s){const c=s==="RUNNING"?"run":s==="DONE"?"done":s==="PARTIAL"?"part":"unk";return `<span class="badge ${c}">${s==="UNKNOWN"?"CHƯA RÕ":s}</span>`}\n',
))

# 7. JS: eval render before ledger render
REPLACEMENTS.append((
    "  if(d.ledger&&d.ledger.length){",
    EVAL_RENDER + "  if(d.ledger&&d.ledger.length){",
))

for i, (old, new) in enumerate(REPLACEMENTS):
    n = src.count(old)
    assert n == 1, f"replacement {i}: anchor found {n} times (expected 1)"
    src = src.replace(old, new)

assert src != orig
shutil.copy(P, P.with_name("server.py.bak-eval-20261120"))
P.write_text(src)
print(f"dashboard server.py patched OK ({len(REPLACEMENTS)} replacements), backup at server.py.bak-eval-20261120")