File size: 12,361 Bytes
f789875
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Feishu webhook monitor for long-running Perturb benchmarks.

Watches a benchmark output directory, counts completed samples, estimates ETA,
and sends Feishu (Lark) notifications on progress, abnormal exit, or completion.

Usage:
    # Use env var for webhook
    export FEISHU_WEBHOOK_URL="https://open.feishu.cn/open-apis/bot/v2/hook/xxxx"
    python scripts/monitor_benchmark_feishu.py \
        --output-dir /workspace/Perturb/benchmark_2000_v15 \
        --interval-minutes 30

    # Or pass webhook directly
    python scripts/monitor_benchmark_feishu.py \
        --output-dir /workspace/Perturb/benchmark_2000_v15 \
        --webhook https://open.feishu.cn/open-apis/bot/v2/hook/xxxx
"""

from __future__ import annotations

import argparse
import json
import os
import sys
import time
from datetime import datetime, timedelta
from pathlib import Path

import requests


def send_feishu(webhook_url: str, text: str) -> bool:
    """Send a plain text message to a Feishu webhook."""
    if not webhook_url or webhook_url.startswith("https://YOUR_"):
        print(f"[feishu skip] webhook not configured. Message would be:\n{text}")
        return False
    payload = {
        "msg_type": "text",
        "content": {"text": text},
    }
    try:
        resp = requests.post(webhook_url, json=payload, timeout=10)
        resp.raise_for_status()
        print(f"[feishu ok] {resp.status_code} {resp.text[:120]}")
        return True
    except Exception as exc:
        print(f"[feishu err] {exc}")
        return False


def read_indices(output_dir: Path) -> tuple[int, list[int]] | None:
    """Return (total, indices) from indices.json if it exists."""
    path = output_dir / "indices.json"
    if not path.exists():
        return None
    try:
        data = json.loads(path.read_text())
        if isinstance(data, list):
            return len(data), data
        return int(data.get("n", 0)), data.get("indices", [])
    except Exception as exc:
        print(f"[warn] failed to read indices.json: {exc}")
        return None


def count_completed(output_dir: Path, subdir: str) -> int:
    """Count completed *.json files under output_dir/subdir."""
    target = output_dir / subdir
    if not target.exists():
        return 0
    return len(list(target.glob("*.json")))


def read_summary(output_dir: Path, subdir: str) -> dict | None:
    """Read summary.json if available; fall back to aggregating summary_worker*.json."""
    target_dir = output_dir / subdir
    path = target_dir / "summary.json"
    if path.exists():
        try:
            return json.loads(path.read_text())
        except Exception:
            pass

    # Multi-worker mode: aggregate per-worker summaries.
    worker_summaries = []
    for ws_path in sorted(target_dir.glob("summary_worker*.json")):
        try:
            worker_summaries.append(json.loads(ws_path.read_text()))
        except Exception:
            pass
    if not worker_summaries:
        return None

    total_n = sum(ws.get("n", 0) for ws in worker_summaries)
    if total_n == 0:
        return None

    avg_score = sum(ws.get("avg_score", 0.0) * ws.get("n", 0) for ws in worker_summaries) / total_n
    success_rate = sum(ws.get("success_rate", 0.0) * ws.get("n", 0) for ws in worker_summaries) / total_n
    return {
        "n": total_n,
        "avg_score": avg_score,
        "success_rate": success_rate,
        "workers": len(worker_summaries),
        "aggregated": True,
    }


def process_alive(pids: list[int]) -> tuple[bool, list[int]]:
    """Return (any_alive, list_of_alive_pids)."""
    alive = []
    for pid in pids:
        try:
            os.kill(pid, 0)
            alive.append(pid)
        except (OSError, ProcessLookupError):
            pass
    return bool(alive), alive


def parse_pids(raw: str) -> list[int]:
    """Parse a comma-separated list of PIDs."""
    return [int(x.strip()) for x in raw.split(",") if x.strip().isdigit()]


def load_pids_file(path: Path) -> list[int]:
    """Load PIDs from a file, one per line or comma-separated."""
    if not path.exists():
        return []
    pids = []
    for line in path.read_text().splitlines():
        pids.extend(parse_pids(line))
    return pids


def format_eta(seconds: float) -> str:
    """Format remaining seconds as a human readable string."""
    if seconds < 0 or not seconds:
        return "unknown"
    delta = timedelta(seconds=int(seconds))
    hours, remainder = divmod(delta.total_seconds(), 3600)
    minutes, seconds = divmod(remainder, 60)
    parts = []
    if hours:
        parts.append(f"{int(hours)}h")
    if minutes:
        parts.append(f"{int(minutes)}m")
    if seconds or not parts:
        parts.append(f"{int(seconds)}s")
    return "".join(parts)


def build_progress_message(
    *,
    output_dir: Path,
    subdir: str,
    total: int,
    completed: int,
    pids: list[int],
    elapsed_seconds: float,
) -> str:
    """Build a Feishu progress notification text."""
    pct = completed / total * 100 if total else 0.0
    avg_per_image = elapsed_seconds / completed if completed else 0.0
    remaining = (total - completed) * avg_per_image if completed else 0.0
    eta = format_eta(remaining)
    summary = read_summary(output_dir, subdir)
    score_line = ""
    if summary:
        avg = summary.get("avg_score", 0.0)
        succ = summary.get("success_rate", 0.0) * 100
        score_line = f"\n当前已跑完均分: {avg:.4f} | 成功率: {succ:.1f}%"

    any_alive, alive_pids = process_alive(pids)
    pid_line = f"PIDs: {','.join(str(p) for p in pids)}" if pids else "PID: not tracked"
    status = f"running ({len(alive_pids)}/{len(pids)} workers alive)" if any_alive else "⚠️ all workers gone"

    return (
        f"🤖 Perturb benchmark 进度更新\n"
        f"目录: {output_dir}/{subdir}\n"
        f"{pid_line}\n"
        f"状态: {status}\n"
        f"进度: {completed}/{total} ({pct:.1f}%)\n"
        f"已用时间: {format_eta(elapsed_seconds)}\n"
        f"单图平均: {avg_per_image:.1f}s\n"
        f"预计剩余: {eta}{score_line}"
    )


def build_completion_message(
    *,
    output_dir: Path,
    subdir: str,
    total: int,
    completed: int,
    elapsed_seconds: float,
    aborted: bool = False,
) -> str:
    """Build completion or abort notification text."""
    summary = read_summary(output_dir, subdir)
    if summary:
        avg = summary.get("avg_score", 0.0)
        succ = summary.get("success_rate", 0.0) * 100
        score_line = f"均分: {avg:.4f} | 成功率: {succ:.1f}%"
    else:
        score_line = "summary.json 尚未生成"

    if aborted:
        emoji = "🚨"
        header = "benchmark 异常退出"
        extra = f"只完成了 {completed}/{total}"
    else:
        emoji = "✅"
        header = "benchmark 已完成"
        extra = f"全部 {total}/{total} 完成"

    return (
        f"{emoji} Perturb {header}\n"
        f"目录: {output_dir}/{subdir}\n"
        f"{extra}\n"
        f"总耗时: {format_eta(elapsed_seconds)}\n"
        f"{score_line}"
    )


def monitor(
    *,
    output_dir: Path,
    subdir: str,
    webhook_url: str,
    interval_seconds: float,
    pids: list[int],
) -> None:
    """Main monitoring loop."""
    indices_info = read_indices(output_dir)
    if indices_info is None:
        # Fallback: wait and retry a few times in case indices.json is not written yet.
        for _ in range(10):
            time.sleep(5)
            indices_info = read_indices(output_dir)
            if indices_info is not None:
                break
    if indices_info is None:
        msg = f"❌ 监控启动失败:未找到 {output_dir}/indices.json"
        send_feishu(webhook_url, msg)
        raise RuntimeError(msg)

    total, _ = indices_info
    start_time = time.time()
    last_report_time = start_time
    last_completed = 0

    # Initial notification
    send_feishu(
        webhook_url,
        f"🚀 Perturb benchmark 监控已启动\n"
        f"目录: {output_dir}/{subdir}\n"
        f"总样本数: {total}\n"
        f"推送间隔: {interval_seconds/60:.0f} 分钟\n"
        f"开始时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
    )

    completed = count_completed(output_dir, subdir)
    while True:
        time.sleep(min(30, interval_seconds))
        now = time.time()
        elapsed = now - start_time
        completed = count_completed(output_dir, subdir)

        # Check if all watched processes died
        any_alive, alive_pids = process_alive(pids)
        if pids and not any_alive:
            aborted = completed < total
            msg = build_completion_message(
                output_dir=output_dir,
                subdir=subdir,
                total=total,
                completed=completed,
                elapsed_seconds=elapsed,
                aborted=aborted,
            )
            send_feishu(webhook_url, msg)
            print(f"[monitor] all workers exited. completed={completed}/{total}")
            return

        # Periodic progress report
        if now - last_report_time >= interval_seconds:
            msg = build_progress_message(
                output_dir=output_dir,
                subdir=subdir,
                total=total,
                completed=completed,
                pids=pids,
                elapsed_seconds=elapsed,
            )
            send_feishu(webhook_url, msg)
            last_report_time = now

        # Detect completion
        if completed >= total:
            msg = build_completion_message(
                output_dir=output_dir,
                subdir=subdir,
                total=total,
                completed=completed,
                elapsed_seconds=elapsed,
                aborted=False,
            )
            send_feishu(webhook_url, msg)
            print(f"[monitor] benchmark completed. {completed}/{total}")
            return

        # Print local heartbeat
        if completed != last_completed:
            print(
                f"[{datetime.now().strftime('%H:%M:%S')}] completed={completed}/{total} "
                f"elapsed={format_eta(elapsed)} alive_workers={len(alive_pids)}/{len(pids)}"
            )
            last_completed = completed


def main() -> None:
    parser = argparse.ArgumentParser(description="Feishu monitor for Perturb benchmark")
    parser.add_argument(
        "--output-dir",
        type=Path,
        default=Path("/workspace/Perturb/benchmark_2000_v15"),
        help="Benchmark output directory",
    )
    parser.add_argument(
        "--subdir",
        type=str,
        default="v15",
        help="Subdirectory containing per-image json files",
    )
    parser.add_argument(
        "--webhook",
        type=str,
        default=os.getenv("FEISHU_WEBHOOK_URL", "https://open.feishu.cn/open-apis/bot/v2/hook/b1c64e78-6277-40e6-aed0-795a5c72deb6"),
        help="Feishu webhook URL (or set FEISHU_WEBHOOK_URL env var)",
    )
    parser.add_argument(
        "--interval-minutes",
        type=float,
        default=30.0,
        help="Progress report interval in minutes",
    )
    parser.add_argument(
        "--pid",
        type=str,
        default=None,
        help="Comma-separated process IDs to watch (optional; auto-detected if omitted)",
    )
    args = parser.parse_args()

    webhook = args.webhook
    if not webhook:
        print("[warn] FEISHU_WEBHOOK_URL not set; messages will be printed to stdout only.")

    pids: list[int] = []
    if args.pid:
        pids = parse_pids(args.pid)
    else:
        # Try to auto-detect from pids.txt or legacy pid.txt next to the output dir.
        candidates = [
            args.output_dir.parent / f"{args.output_dir.name}_logs" / "pids.txt",
            args.output_dir.parent / f"{args.output_dir.name}_logs" / "pid.txt",
            args.output_dir / "pids.txt",
            args.output_dir / "pid.txt",
        ]
        for cand in candidates:
            if cand.exists():
                pids = load_pids_file(cand)
                if pids:
                    print(f"[info] auto-detected pids={pids} from {cand}")
                    break

    monitor(
        output_dir=args.output_dir,
        subdir=args.subdir,
        webhook_url=webhook,
        interval_seconds=args.interval_minutes * 60,
        pids=pids,
    )


if __name__ == "__main__":
    main()