Blame view

scripts/evaluation/eval_framework/static/eval_web.js 10.5 KB
7ddd4cb3   tangwang   评估体系从三等级->四等级 Exa...
1
2
3
4
5
6
7
8
9
10
11
  async function fetchJSON(url, options) {
    const res = await fetch(url, options);
    if (!res.ok) throw new Error(await res.text());
    return await res.json();
  }
  
  function fmtNumber(value, digits = 3) {
    if (value == null || Number.isNaN(Number(value))) return "-";
    return Number(value).toFixed(digits);
  }
  
30b490e1   tangwang   添加ERR评估指标
12
13
14
15
  function metricColumns(metrics) {
    const defs = [
      { title: "NDCG", keys: ["NDCG@5", "NDCG@10", "NDCG@20", "NDCG@50"] },
      { title: "ERR", keys: ["ERR@5", "ERR@10", "ERR@20", "ERR@50"] },
7ddd4cb3   tangwang   评估体系从三等级->四等级 Exa...
16
      {
30b490e1   tangwang   添加ERR评估指标
17
18
19
20
21
22
23
24
        title: "Top slot",
        keys: [
          "Exact_Precision@5",
          "Exact_Precision@10",
          "Strong_Precision@5",
          "Strong_Precision@10",
          "Strong_Precision@20",
        ],
7ddd4cb3   tangwang   评估体系从三等级->四等级 Exa...
25
26
      },
      {
30b490e1   tangwang   添加ERR评估指标
27
28
29
30
31
32
33
34
35
        title: "Recall",
        keys: [
          "Useful_Precision@10",
          "Useful_Precision@20",
          "Useful_Precision@50",
          "Gain_Recall@10",
          "Gain_Recall@20",
          "Gain_Recall@50",
        ],
7ddd4cb3   tangwang   评估体系从三等级->四等级 Exa...
36
37
      },
      {
30b490e1   tangwang   添加ERR评估指标
38
39
40
41
42
43
44
45
46
47
        title: "First good",
        keys: [
          "Exact_Success@5",
          "Exact_Success@10",
          "Strong_Success@5",
          "Strong_Success@10",
          "MRR_Exact@10",
          "MRR_Strong@10",
          "Avg_Grade@10",
        ],
7ddd4cb3   tangwang   评估体系从三等级->四等级 Exa...
48
49
50
      },
    ];
    const seen = new Set();
30b490e1   tangwang   添加ERR评估指标
51
52
53
    const columns = defs
      .map((col) => {
        const rows = col.keys
7ddd4cb3   tangwang   评估体系从三等级->四等级 Exa...
54
55
56
57
58
          .filter((key) => metrics && Object.prototype.hasOwnProperty.call(metrics, key))
          .map((key) => {
            seen.add(key);
            return [key, metrics[key]];
          });
30b490e1   tangwang   添加ERR评估指标
59
        return { title: col.title, rows };
7ddd4cb3   tangwang   评估体系从三等级->四等级 Exa...
60
      })
30b490e1   tangwang   添加ERR评估指标
61
62
63
64
65
66
67
      .filter((col) => col.rows.length);
    const rest = Object.keys(metrics || {})
      .filter((key) => !seen.has(key))
      .sort()
      .map((key) => [key, metrics[key]]);
    if (rest.length) columns.push({ title: "Other", rows: rest });
    return columns;
7ddd4cb3   tangwang   评估体系从三等级->四等级 Exa...
68
69
70
71
72
73
  }
  
  function renderMetrics(metrics, metricContext) {
    const root = document.getElementById("metrics");
    root.innerHTML = "";
    const ctx = document.getElementById("metricContext");
30b490e1   tangwang   添加ERR评估指标
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
    const parts = [];
    if (metricContext && metricContext.primary_metric) {
      parts.push(`Primary: ${metricContext.primary_metric}`);
    }
    if (metricContext && metricContext.gain_scheme) {
      parts.push(
        `NDCG gains: ${Object.entries(metricContext.gain_scheme)
          .map(([label, gain]) => `${label}=${gain}`)
          .join(", ")}`
      );
    }
    if (metricContext && metricContext.stop_prob_scheme) {
      parts.push(
        `ERR P(stop): ${Object.entries(metricContext.stop_prob_scheme)
          .map(([label, p]) => `${label}=${p}`)
          .join(", ")}`
      );
    }
    ctx.textContent = parts.length ? `${parts.join(". ")}.` : "";
7ddd4cb3   tangwang   评估体系从三等级->四等级 Exa...
93
  
30b490e1   tangwang   添加ERR评估指标
94
95
96
97
98
99
100
101
102
103
104
105
106
107
    const bar = document.createElement("div");
    bar.className = "metrics-columns";
    metricColumns(metrics || {}).forEach((col) => {
      const column = document.createElement("div");
      column.className = "metric-column";
      const h = document.createElement("h4");
      h.className = "metric-column-title";
      h.textContent = col.title;
      column.appendChild(h);
      col.rows.forEach(([key, value]) => {
        const row = document.createElement("div");
        row.className = "metric-row";
        row.innerHTML = `<span class="metric-row-name">${key}:</span> <span class="metric-row-value">${fmtNumber(value)}</span>`;
        column.appendChild(row);
c81b0fc1   tangwang   scripts/evaluatio...
108
      });
30b490e1   tangwang   添加ERR评估指标
109
      bar.appendChild(column);
7ddd4cb3   tangwang   评估体系从三等级->四等级 Exa...
110
    });
30b490e1   tangwang   添加ERR评估指标
111
    root.appendChild(bar);
7ddd4cb3   tangwang   评估体系从三等级->四等级 Exa...
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
  }
  
  function labelBadgeClass(label) {
    if (!label || label === "Unknown") return "badge-unknown";
    return "label-" + String(label).toLowerCase().replace(/\s+/g, "-");
  }
  
  function renderResults(results, rootId = "results", showRank = true) {
    const mount = document.getElementById(rootId);
    mount.innerHTML = "";
    (results || []).forEach((item) => {
      const label = item.label || "Unknown";
      const box = document.createElement("div");
      box.className = "result";
      box.innerHTML = `
        <div><span class="badge ${labelBadgeClass(label)}">${label}</span><div class="muted" style="margin-top:8px">${showRank ? `#${item.rank || "-"}` : (item.rerank_score != null ? `rerank=${item.rerank_score.toFixed ? item.rerank_score.toFixed(4) : item.rerank_score}` : "not recalled")}</div></div>
        <img class="thumb" src="${item.image_url || ""}" alt="" />
        <div>
          <div class="title">${item.title || ""}</div>
          ${item.title_zh ? `<div class="title-zh">${item.title_zh}</div>` : ""}
          <div class="options">
            <div>${(item.option_values || [])[0] || ""}</div>
            <div>${(item.option_values || [])[1] || ""}</div>
            <div>${(item.option_values || [])[2] || ""}</div>
          </div>
        </div>`;
      mount.appendChild(box);
    });
    if (!(results || []).length) {
      mount.innerHTML = '<div class="muted">None.</div>';
    }
  }
  
  function renderTips(data) {
    const root = document.getElementById("tips");
    const tips = [...(data.tips || [])];
    const stats = data.label_stats || {};
    tips.unshift(
      `Cached labels: ${stats.total || 0}. Recalled hits: ${stats.recalled_hits || 0}. Missed judged useful results: ${stats.missing_relevant_count || 0} (Exact ${stats.missing_exact_count || 0}, High ${stats.missing_high_count || 0}, Low ${stats.missing_low_count || 0}).`
    );
    root.innerHTML = tips.map((text) => `<div class="tip">${text}</div>`).join("");
  }
  
  async function loadQueries() {
    const data = await fetchJSON("/api/queries");
    const root = document.getElementById("queryList");
    root.innerHTML = "";
    data.queries.forEach((query) => {
      const btn = document.createElement("button");
      btn.className = "query-item";
      btn.textContent = query;
      btn.onclick = () => {
        document.getElementById("queryInput").value = query;
        runSingle();
      };
      root.appendChild(btn);
    });
  }
  
  function historySummaryHtml(meta) {
    const m = meta && meta.aggregate_metrics;
    const nq = (meta && meta.queries && meta.queries.length) || (meta && meta.per_query && meta.per_query.length) || null;
    const parts = [];
    if (nq != null) parts.push(`<span>Queries</span> ${nq}`);
    if (m && m["NDCG@10"] != null) parts.push(`<span>NDCG@10</span> ${fmtNumber(m["NDCG@10"])}`);
30b490e1   tangwang   添加ERR评估指标
177
    if (m && m["ERR@10"] != null) parts.push(`<span>ERR@10</span> ${fmtNumber(m["ERR@10"])}`);
7ddd4cb3   tangwang   评估体系从三等级->四等级 Exa...
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
    if (m && m["Strong_Precision@10"] != null) parts.push(`<span>Strong@10</span> ${fmtNumber(m["Strong_Precision@10"])}`);
    if (m && m["Gain_Recall@50"] != null) parts.push(`<span>Gain Recall@50</span> ${fmtNumber(m["Gain_Recall@50"])}`);
    if (!parts.length) return "";
    return `<div class="hstats">${parts.join(" · ")}</div>`;
  }
  
  async function loadHistory() {
    const data = await fetchJSON("/api/history");
    const root = document.getElementById("history");
    root.classList.remove("muted");
    const items = data.history || [];
    if (!items.length) {
      root.innerHTML = '<span class="muted">No history yet.</span>';
      return;
    }
    root.innerHTML = `<div class="history-list"></div>`;
    const list = root.querySelector(".history-list");
    items.forEach((item) => {
      const btn = document.createElement("button");
      btn.type = "button";
      btn.className = "history-item";
      btn.setAttribute("aria-label", `Open report ${item.batch_id}`);
      const sum = historySummaryHtml(item.metadata);
      btn.innerHTML = `<div class="hid">${item.batch_id}</div>
        <div class="hmeta">${item.created_at} · tenant ${item.tenant_id}</div>${sum}`;
      btn.onclick = () => openBatchReport(item.batch_id);
      list.appendChild(btn);
    });
  }
  
  let _lastReportPath = "";
  
  function closeReportModal() {
    const el = document.getElementById("reportModal");
    el.classList.remove("is-open");
    el.setAttribute("aria-hidden", "true");
    document.getElementById("reportModalBody").innerHTML = "";
    document.getElementById("reportModalMeta").textContent = "";
  }
  
  async function openBatchReport(batchId) {
    const el = document.getElementById("reportModal");
    const body = document.getElementById("reportModalBody");
    const metaEl = document.getElementById("reportModalMeta");
    const titleEl = document.getElementById("reportModalTitle");
    el.classList.add("is-open");
    el.setAttribute("aria-hidden", "false");
    titleEl.textContent = batchId;
    metaEl.textContent = "";
    body.className = "report-modal-body batch-report-md report-modal-loading";
    body.textContent = "Loading report…";
    try {
      const rep = await fetchJSON("/api/history/" + encodeURIComponent(batchId) + "/report");
      _lastReportPath = rep.report_markdown_path || "";
      metaEl.textContent = rep.report_markdown_path || "";
      const raw = marked.parse(rep.markdown || "", { gfm: true });
      const safe = DOMPurify.sanitize(raw, { USE_PROFILES: { html: true } });
      body.className = "report-modal-body batch-report-md";
      body.innerHTML = safe;
    } catch (e) {
      body.className = "report-modal-body report-modal-error";
      body.textContent = e && e.message ? e.message : String(e);
    }
  }
  
  document.getElementById("reportModal").addEventListener("click", (ev) => {
    if (ev.target && ev.target.getAttribute("data-close-report") === "1") closeReportModal();
  });
  
  document.addEventListener("keydown", (ev) => {
    if (ev.key === "Escape") closeReportModal();
  });
  
  document.getElementById("reportCopyPath").addEventListener("click", async () => {
    if (!_lastReportPath) return;
    try {
      await navigator.clipboard.writeText(_lastReportPath);
    } catch (_) {}
  });
  
  async function runSingle() {
    const query = document.getElementById("queryInput").value.trim();
    if (!query) return;
    document.getElementById("status").textContent = `Evaluating "${query}"...`;
    const data = await fetchJSON("/api/search-eval", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ query, top_k: 100, auto_annotate: false }),
    });
    document.getElementById("status").textContent = `Done. total=${data.total}`;
    renderMetrics(data.metrics, data.metric_context);
    renderResults(data.results, "results", true);
    renderResults(data.missing_relevant, "missingRelevant", false);
    renderTips(data);
    loadHistory();
  }
  
  async function runBatch() {
    document.getElementById("status").textContent = "Running batch evaluation...";
    const data = await fetchJSON("/api/batch-eval", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ top_k: 100, auto_annotate: false }),
    });
    document.getElementById("status").textContent = `Batch done. report=${data.batch_id}`;
    renderMetrics(data.aggregate_metrics, data.metric_context);
    renderResults([], "results", true);
    renderResults([], "missingRelevant", false);
    document.getElementById("tips").innerHTML = '<div class="tip">Batch evaluation uses cached labels only unless force refresh is requested via CLI/API.</div>';
    loadHistory();
  }
  
  loadQueries();
  loadHistory();