File size: 5,642 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
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
from __future__ import annotations

import json
import math
from dataclasses import dataclass
from datetime import UTC, datetime
from typing import Any

import requests


@dataclass(frozen=True)
class CurrentTask:
    task_id: str
    image_url: str


@dataclass(frozen=True)
class SubmittedResponse:
    miner_uid: int
    image_url: str
    image_hash: str = ""


def _url(base_url: str, path: str) -> str:
    return f"{base_url.rstrip('/')}/{path.lstrip('/')}"


def _json_response(response: requests.Response) -> Any:
    if response.status_code < 200 or response.status_code >= 300:
        raise RuntimeError(f"HTTP {response.status_code}: {response.text[:200]}")
    if not response.text.strip():
        return None
    return response.json()


def _image_url_from_payload(payload: dict[str, Any]) -> str:
    return str(payload.get("imageURL") or payload.get("imageUrl") or payload.get("image_url") or "").strip()


def _image_hash_from_payload(payload: dict[str, Any]) -> str:
    return str(payload.get("imageHash") or payload.get("image_hash") or "").strip().lower()


def sign_body(wallet: Any, body: bytes) -> str:
    hotkey = getattr(wallet, "hotkey", None)
    if hotkey is None or not hasattr(hotkey, "sign"):
        raise RuntimeError("Wallet hotkey does not support request signing.")
    signature = hotkey.sign(body)
    if isinstance(signature, bytes):
        return "0x" + signature.hex()
    if isinstance(signature, str):
        return signature if signature.startswith("0x") else "0x" + signature
    if hasattr(signature, "hex"):
        return "0x" + signature.hex()
    raise RuntimeError(f"Unsupported signature type: {type(signature).__name__}")


def _authorization_headers(api_key: str) -> dict[str, str]:
    api_key = str(api_key).strip()
    if not api_key:
        return {}
    return {"Authorization": f"Bearer {api_key}"}


def get_current_task(*, base_url: str, timeout_seconds: float) -> CurrentTask | None:
    response = requests.get(_url(base_url, "/task"), timeout=timeout_seconds)
    payload = _json_response(response)
    if not isinstance(payload, dict):
        return None
    task_id = str(payload.get("task_id") or payload.get("taskId") or "").strip()
    image_url = _image_url_from_payload(payload)
    if not task_id or not image_url:
        return None
    return CurrentTask(task_id=task_id, image_url=image_url)


def post_task(
    *,
    base_url: str,
    api_key: str,
    task_id: str,
    image_url: str,
    status: str,
    hotkeys: list[str],
    timeout_seconds: float,
) -> Any:
    payload = {"task_id": task_id, "imageURL": image_url, "status": status, "hotkeys": hotkeys}
    response = requests.post(
        _url(base_url, "/task"),
        json=payload,
        headers=_authorization_headers(api_key),
        timeout=timeout_seconds,
    )
    return _json_response(response)


def submit_miner_response(
    *,
    base_url: str,
    wallet: Any,
    image_url: str,
    image_hash: str,
    timeout_seconds: float,
) -> Any:
    hotkey = str(getattr(getattr(wallet, "hotkey", None), "ss58_address", ""))
    payload = {
        "miner_hotkey": hotkey,
        "timestamp": datetime.now(UTC).isoformat(),
        "imageURL": image_url,
        "imageHash": str(image_hash).strip().lower(),
    }
    body = json.dumps(payload, separators=(",", ":")).encode("utf-8")
    response = requests.post(
        _url(base_url, "/submits"),
        data=body,
        headers={
            "Content-Type": "application/json",
            "X-Miner-Hotkey": hotkey,
            "X-Signature": sign_body(wallet, body),
        },
        timeout=timeout_seconds,
    )
    return _json_response(response)


def get_leaderboard_avg_scores(
    *,
    base_url: str,
    validator_hotkey: str,
    timeout_seconds: float,
) -> dict[int, float]:
    """Return miner uid -> avgScore from one validator's leaderboard report."""
    response = requests.get(
        _url(base_url, f"/leaderboard/{validator_hotkey}"),
        timeout=timeout_seconds,
    )
    payload = _json_response(response)
    if not isinstance(payload, dict):
        return {}
    raw_miners = payload.get("miners")
    if not isinstance(raw_miners, list):
        return {}
    scores: dict[int, float] = {}
    for item in raw_miners:
        if not isinstance(item, dict):
            continue
        try:
            uid = int(item.get("uid"))
            avg_score = float(item.get("avgScore", item.get("avg_score")))
        except (TypeError, ValueError):
            continue
        if math.isfinite(avg_score):
            scores[uid] = avg_score
    return scores


def get_submitted_responses(*, base_url: str, api_key: str, timeout_seconds: float) -> list[SubmittedResponse]:
    response = requests.get(
        _url(base_url, "/submits"),
        headers=_authorization_headers(api_key),
        timeout=timeout_seconds,
    )
    payload = _json_response(response)
    if not isinstance(payload, list):
        return []

    responses: list[SubmittedResponse] = []
    for item in payload:
        if not isinstance(item, dict):
            continue
        raw_uid = item.get("miner_uid", item.get("miner_id", item.get("minerUid")))
        image_url = _image_url_from_payload(item)
        try:
            miner_uid = int(raw_uid)
        except (TypeError, ValueError):
            continue
        if image_url:
            responses.append(
                SubmittedResponse(
                    miner_uid=miner_uid,
                    image_url=image_url,
                    image_hash=_image_hash_from_payload(item),
                )
            )
    return responses