File size: 5,159 Bytes
152228b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Dataset builder: for every SETTLED leaderboard task where OUR miner (UID137) scored NON-ZERO,
save the real clean input + the exact output PNG of EVERY miner that scored higher than us, plus
full per-task score metadata. Builds a large local-syncable dataset of "better-than-us" samples for
training / replay.

Layout under <out>/:
  inputs/<row>.png              real task clean (from our miner log's image_url, valid ~7 days)
  <uid>/<row>.png               that miner's exact submitted output (only miners above us)
  meta/<row>.json               {row, task_id, our: {...}, miners: [{uid,score,rmse,margin,norm}...]}
  manifest.jsonl                one row per (row,uid) above us  (append-only index)
"""
from __future__ import annotations
import io, json, os, re, sys, time, urllib.request
from pathlib import Path

OUT = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("/root/edge_cases")
OUR_UID = "137"
API = "https://api.perturbai.io/api/v1"
LOGS = ["/root/miner_live.log", "/root/miner_live_preGF.log", "/root/miner_live_preReplay.log"]
for d in ("inputs", "meta"):
    (OUT / d).mkdir(parents=True, exist_ok=True)
MANIFEST = OUT / "manifest.jsonl"

def get(u, t=15):
    return json.loads(urllib.request.urlopen(urllib.request.Request(u, headers={"User-Agent": "ds"}), timeout=t).read().decode())
def getbytes(u, t=25):
    return urllib.request.urlopen(urllib.request.Request(u, headers={"User-Agent": "ds"}), timeout=t).read()
def validators():
    try: return list(get(f"{API}/validators").get("validators", []))
    except Exception: return []
def leaderboard():
    for hk in validators():
        try:
            d = get(f"{API}/leaderboard/{hk}")
            if d.get("miners"): return d
        except Exception: continue
    return None
def row_of(tid): return int(tid.split("-")[-1])

_clean_url_cache = {}
def clean_url_for_row(row):
    if row in _clean_url_cache: return _clean_url_cache[row]
    pat = re.compile(r"-0*%d image_url=(\S+)" % row)
    for lg in LOGS:
        try:
            for line in open(lg):
                m = pat.search(line)
                if m:
                    _clean_url_cache[row] = m.group(1); return m.group(1)
        except FileNotFoundError: pass
    _clean_url_cache[row] = None; return None

seen = set()
if MANIFEST.exists():
    for line in open(MANIFEST):
        try:
            r = json.loads(line); seen.add((r["row"], str(r["uid"])))
        except Exception: pass

def process(lb):
    task_id = lb.get("taskId")
    if not task_id: return 0
    row = row_of(task_id)
    miners = lb.get("miners", [])
    ours = next((m for m in miners if str(m.get("uid")) == OUR_UID), None)
    our_score = float(ours.get("lastScore") or 0) if ours else 0.0
    # gate: only tasks where WE have a non-zero valid score
    if not ours or ours.get("result") != "Valid" or our_score <= 0.0:
        return 0
    # per-task metadata (all miners)
    meta = {"row": row, "task_id": task_id,
            "our": {"score": our_score, "rmse": float(ours.get("rmse") or 0),
                    "margin": float(ours.get("margin") or 0), "norm": float(ours.get("norm") or 0)},
            "miners": [{"uid": str(m.get("uid")), "score": float(m.get("lastScore") or 0),
                        "rmse": float(m.get("rmse") or 0), "margin": float(m.get("margin") or 0),
                        "norm": float(m.get("norm") or 0), "result": m.get("result")}
                       for m in miners]}
    (OUT / "meta" / f"{row}.json").write_text(json.dumps(meta))
    # real clean input
    if not (OUT / "inputs" / f"{row}.png").exists():
        cu = clean_url_for_row(row)
        if cu:
            try: (OUT / "inputs" / f"{row}.png").write_bytes(getbytes(cu))
            except Exception: pass
    saved = 0
    for m in miners:
        uid = str(m.get("uid"))
        if uid == OUR_UID: continue
        sc = float(m.get("lastScore") or 0)
        if sc <= our_score + 1e-9 or m.get("result") != "Valid": continue
        if (row, uid) in seen: continue
        url = m.get("imageUrl") or m.get("imageURL")
        if not url: continue
        try: data = getbytes(url)
        except Exception: continue
        (OUT / uid).mkdir(exist_ok=True)
        (OUT / uid / f"{row}.png").write_bytes(data)
        with open(MANIFEST, "a") as f:
            f.write(json.dumps({"row": row, "uid": uid, "score": sc, "our_score": our_score,
                                "rmse": float(m.get("rmse") or 0), "margin": float(m.get("margin") or 0),
                                "norm": float(m.get("norm") or 0), "task_id": task_id, "ts": time.time()}) + "\n")
        seen.add((row, uid)); saved += 1
    return saved

if __name__ == "__main__":
    last = None
    while True:
        try:
            lb = leaderboard()
            t = lb.get("taskId") if lb else None
            if t and t != last:
                n = process(lb); last = t
                print(f"{time.strftime('%H:%M:%S')} task row={row_of(t)} saved {n} (total manifest={sum(1 for _ in open(MANIFEST)) if MANIFEST.exists() else 0})", flush=True)
        except Exception as e:
            print("err", e, flush=True)
        time.sleep(15)