Spaces:
Running
Running
feat(analytics): xếp hạng tool đóng góp nhiều/ít nhất; tạm ẩn bảng B2
Browse filesĐiểm đóng góp mỗi tool (etl.score_contribution), trọng số nghiệp vụ chốt:
40% nhu cầu người dùng — số việc người giao cho tool
20% ít phải bấm chạy lại — A4 nghịch đảo, làm 1 phát ăn ngay = điểm cao
40% sản phẩm đầu ra — B1
Mỗi thành phần quy về thang 100 theo tool cao nhất TRONG KỲ ĐANG LỌC, nên
điểm chỉ so được giữa các tool cùng khoảng thời gian. Tool chưa chạy việc
nào = 0 điểm.
Giao diện: thẻ "🏆 Tool đóng góp nhiều nhất / ít nhất" — 2 ô nổi bật + bảng
đủ 3 điểm thành phần (có thanh tỷ lệ) để đối chiếu vì sao ra thứ hạng đó.
Tạm ẩn (comment) bảng "Tốc độ máy mỗi bước (B2)" theo yêu cầu; backend vẫn
tính và trả data.jobs như cũ, muốn hiện lại chỉ cần bỏ comment.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Files changed (3)
43 unmodified lines444546474849229 unmodified lines27928028128228328464 unmodified lines34935035135235335472 unmodified lines42742842943043143243 unmodified lines# Event tính là "một lần bấm/hỏi" cho chỉ số A4.ATTEMPT_EVENTS = {"job_done", "regenerate", "edit_request"}# ── Tiện ích thống kê ────────────────────────────────────────────229 unmodified lines}def summarize(events: list[dict]) -> dict:"""Toàn bộ số liệu cho tab "Quản lý thời lượng"."""tasks = build_tasks(events)64 unmodified lines**_bucket_metrics(ft),})features.sort(key=lambda f: -f["tasks"])# Tốc độ máy từng loại job (B2)job_ms: dict[str, list[float]] = defaultdict(list)72 unmodified lines"jobs": jobs,"products": product_rows,"timeseries": timeseries,}43 unmodified lines44454647484950515253545556229 unmodified lines28628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632764 unmodified lines39239339439539639739872 unmodified lines47147247347447547647743 unmodified lines# Event tính là "một lần bấm/hỏi" cho chỉ số A4.ATTEMPT_EVENTS = {"job_done", "regenerate", "edit_request"}# ĐIỂM ĐÓNG GÓP của mỗi tool (để xếp "đóng góp nhiều nhất / ít nhất").# Trọng số do bên nghiệp vụ chốt:# 40% nhu cầu người dùng — số việc người giao cho tool (càng nhiều càng cần)# 20% ít phải bấm chạy lại — A4 càng THẤP điểm càng CAO (làm 1 phát ăn ngay)# 40% sản phẩm đầu ra — B1, thứ thật sự mang lại giá trịCONTRIB_WEIGHTS = {"demand": 0.40, "rerun": 0.20, "output": 0.40}# ── Tiện ích thống kê ────────────────────────────────────────────229 unmodified lines}def score_contribution(features: list[dict]) -> None:"""Chấm ĐIỂM ĐÓNG GÓP cho từng tool (ghi thẳng vào từng dict trong `features`).Ba thành phần đều quy về thang 0-100 rồi nhân trọng số CONTRIB_WEIGHTS:- demand: số việc / số việc của tool cao nhất kỳ này.- rerun : số-bấm-ít-nhất / số-bấm-của-tool-này (nghịch đảo -> ít bấm = 100đ).- output: sản phẩm / sản phẩm của tool cao nhất kỳ này.Vì chuẩn hoá theo tool cao nhất TRONG KỲ ĐANG LỌC nên điểm chỉ dùng để SO SÁNHGIỮA CÁC TOOL cùng khoảng thời gian, không so được giữa hai khoảng khác nhau.Tool chưa chạy việc nào -> 0 điểm hết (chưa đóng góp gì thật)."""if not features:returnmax_tasks = max((f["tasks"] for f in features), default=0)max_prod = max((f["produced_total"] for f in features), default=0)# A4 chỉ có nghĩa với tool thật sự có chạy; sàn 1.0 = chạy đúng 1 lần ăn ngay.atts = [max(1.0, f["attempts_avg"] or 1.0) for f in features if f["tasks"]]min_att = min(atts) if atts else 1.0for f in features:if not f["tasks"]:f.update({"score_demand": 0.0, "score_rerun": 0.0,"score_output": 0.0, "score_total": 0.0})continuea = max(1.0, f["attempts_avg"] or 1.0)d = (f["tasks"] / max_tasks * 100.0) if max_tasks else 0.0r = (min_att / a) * 100.0o = (f["produced_total"] / max_prod * 100.0) if max_prod else 0.0f["score_demand"] = round(d, 1)f["score_rerun"] = round(r, 1)f["score_output"] = round(o, 1)f["score_total"] = round(CONTRIB_WEIGHTS["demand"] * d+ CONTRIB_WEIGHTS["rerun"] * r+ CONTRIB_WEIGHTS["output"] * o, 1)def summarize(events: list[dict]) -> dict:"""Toàn bộ số liệu cho tab "Quản lý thời lượng"."""tasks = build_tasks(events)64 unmodified lines**_bucket_metrics(ft),})features.sort(key=lambda f: -f["tasks"])score_contribution(features) # điểm đóng góp nhiều/ít nhất# Tốc độ máy từng loại job (B2)job_ms: dict[str, list[float]] = defaultdict(list)72 unmodified lines"jobs": jobs,"products": product_rows,"timeseries": timeseries,"contrib_weights": CONTRIB_WEIGHTS,}
185 unmodified lines186187188189190191185 unmodified linesassert phases["tts"] == 59000def test_passive_pages_are_not_tasks():"""page_view (trang chủ/hướng dẫn) không có task_id -> không tính vào A3."""evs = _one_full_task() + [185 unmodified lines186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231185 unmodified linesassert phases["tts"] == 59000def test_contribution_score_ranks_tools():"""Điểm đóng góp = 40% nhu cầu + 20% ít bấm chạy lại + 40% sản phẩm đầu ra.Tool A: 2 việc, 4 sản phẩm, mỗi việc bấm 1 lần -> phải đứng trênTool B: 1 việc, 1 sản phẩm, bấm 2 lần/việc."""evs = []for i in (1, 2): # cut: 2 việc, mỗi việc 1 lần bấm, 2 sản phẩmevs += [_ev(i * 10, "feature_open", "open", feature="cut", task=f"c{i}"),_ev(i * 10 + 2, "job_done", "run", feature="cut", task=f"c{i}", lat=1000),_ev(i * 10 + 4, "output_download", "output", feature="cut", task=f"c{i}",value="mp4", count=2),]evs += [ # shuffle: 1 việc, 2 lần bấm, 1 sản phẩm_ev(100, "feature_open", "open", feature="shuffle", task="s1"),_ev(102, "job_done", "run", feature="shuffle", task="s1", lat=1000),_ev(104, "regenerate", "run", feature="shuffle", task="s1"),_ev(106, "output_download", "output", feature="shuffle", task="s1",value="mp4", count=1),]feats = {f["feature"]: f for f in etl.summarize(evs)["features"]}cut, sh = feats["cut"], feats["shuffle"]# cut cao nhất ở cả 3 thành phần -> tròn 100 điểmassert cut["score_demand"] == 100.0 and cut["score_output"] == 100.0assert cut["score_rerun"] == 100.0 and cut["score_total"] == 100.0# shuffle: nhu cầu 1/2, sản phẩm 1/4, bấm gấp đôi -> 0.4*50 + 0.2*50 + 0.4*25assert sh["score_demand"] == 50.0assert sh["score_output"] == 25.0assert sh["score_rerun"] == 50.0assert abs(sh["score_total"] - 40.0) < 0.05assert cut["score_total"] > sh["score_total"]def test_contribution_score_handles_single_tool():"""Chỉ có 1 tool -> không vỡ, tự là tool cao nhất (100 điểm)."""f = etl.summarize(_one_full_task())["features"]assert len(f) == 1 and f[0]["score_total"] == 100.0def test_passive_pages_are_not_tasks():"""page_view (trang chủ/hướng dẫn) không có task_id -> không tính vào A3."""evs = _one_full_task() + [
169 unmodified lines17017117217317417588 unmodified lines26426526626726826927016 unmodified lines28728828929029129237 unmodified lines330331332333334335169 unmodified lines</div></div>{/* Bảng theo tool */}<div className="card"><div className="panel-title">🧪 Chi tiết theo tool</div>88 unmodified lines)}</div>{/* Tốc độ máy */}<div className="card"><div className="panel-title">⚙️ Tốc độ máy mỗi bước (B2)</div><div className="tablewrap">16 unmodified lines</table></div></div>{/* Log thô */}<div className="card">37 unmodified lines);}// ── Nhật ký từng phiên của một người ───────────────────────────function UserSessions({ detail }) {169 unmodified lines17017117217317417517617717888 unmodified lines26726826927027127227327427516 unmodified lines29229329429529629729837 unmodified lines336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432169 unmodified lines</div></div>{/* Tool đóng góp nhiều / ít nhất */}<ContribRanking features={data.features || []} weights={data.contrib_weights} />{/* Bảng theo tool */}<div className="card"><div className="panel-title">🧪 Chi tiết theo tool</div>88 unmodified lines)}</div>{/* TẠM BỎ theo yêu cầu: bảng "Tốc độ máy mỗi bước (B2)". Backend vẫntính và trả `data.jobs` như cũ, muốn hiện lại chỉ cần bỏ comment.<div className="card"><div className="panel-title">⚙️ Tốc độ máy mỗi bước (B2)</div><div className="tablewrap">16 unmodified lines</table></div></div>*/}{/* Log thô */}<div className="card">37 unmodified lines);}// ── Tool đóng góp nhiều / ít nhất ──────────────────────────────// Điểm tổng hợp do backend chấm (etl.score_contribution):// 40% nhu cầu người dùng (số việc) + 20% ít phải bấm chạy lại (A4 nghịch đảo)// + 40% sản phẩm đầu ra (B1). Mỗi phần quy về thang 100 theo tool cao nhất// TRONG KỲ ĐANG LỌC -> chỉ so giữa các tool cùng khoảng, không so giữa 2 khoảng.function ScoreBar({ value, color = "var(--orange)" }) {return (<div style={{ display: "flex", alignItems: "center", gap: 6 }}><div style={{ flex: 1, minWidth: 46, height: 6, borderRadius: 99, background: "var(--line)", overflow: "hidden" }}><div style={{ width: `${Math.max(0, Math.min(100, value || 0))}%`, height: "100%", background: color }} /></div><span className="small" style={{ width: 34, textAlign: "right" }}>{(value ?? 0).toFixed(0)}</span></div>);}function ContribRanking({ features, weights }) {const rows = (features || []).filter((f) => f.tasks).slice().sort((a, b) => (b.score_total ?? 0) - (a.score_total ?? 0));const w = weights || { demand: 0.4, rerun: 0.2, output: 0.4 };const pct = (x) => `${Math.round((x || 0) * 100)}%`;if (!rows.length) {return (<div className="card"><div className="panel-title">🏆 Tool đóng góp nhiều nhất / ít nhất</div><p className="small muted" style={{ margin: 0 }}>Chưa có tool nào chạy việc trong khoảng đã chọn.</p></div>);}const best = rows[0];const worst = rows[rows.length - 1];const card = (title, f, tone) => (<div style={{flex: "1 1 220px", padding: "12px 14px", borderRadius: "var(--radius-sm)",background: tone === "good" ? "var(--green-soft)" : "var(--red-soft)",border: `1px solid ${tone === "good" ? "var(--green)" : "var(--red)"}`,}}><div className="small" style={{ fontWeight: 700, color: tone === "good" ? "var(--green)" : "var(--red)" }}>{title}</div><div style={{ fontSize: 20, fontWeight: 800, margin: "2px 0" }}>{f.label}</div><div className="small muted">{(f.score_total ?? 0).toFixed(1)} điểm · {f.tasks} việc · {fmtNum(f.produced_total)} sản phẩm ·{" "}{f.attempts_avg == null ? "—" : f.attempts_avg.toFixed(1)} lần bấm/việc</div></div>);return (<div className="card"><div className="panel-title">🏆 Tool đóng góp nhiều nhất / ít nhất</div><p className="small muted" style={{ marginTop: -6 }}>Điểm = <b>{pct(w.demand)}</b> nhu cầu người dùng (số việc) + <b>{pct(w.rerun)}</b> ít phải bấm chạy lại(A4 càng thấp điểm càng cao) + <b>{pct(w.output)}</b> số sản phẩm đầu ra (B1).Mỗi phần quy về thang 100 theo tool cao nhất trong khoảng đang lọc — chỉ dùng để so các tool với nhau.</p>{rows.length > 1 && (<div style={{ display: "flex", gap: 12, flexWrap: "wrap", margin: "12px 0" }}>{card("Đóng góp nhiều nhất", best, "good")}{card("Đóng góp ít nhất", worst, "warn")}</div>)}<div className="tablewrap"><table className="list"><thead><tr><th>#</th><th>Tool</th><th>Nhu cầu ({pct(w.demand)})</th><th>Ít chạy lại ({pct(w.rerun)})</th><th>Sản phẩm ({pct(w.output)})</th><th>Tổng điểm</th></tr></thead><tbody>{rows.map((f, i) => (<tr key={f.feature}><td className="small muted">{i + 1}</td><td style={{ fontWeight: 700 }}>{f.label}</td><td style={{ minWidth: 120 }}><ScoreBar value={f.score_demand} /></td><td style={{ minWidth: 120 }}><ScoreBar value={f.score_rerun} color="#3b82f6" /></td><td style={{ minWidth: 120 }}><ScoreBar value={f.score_output} color="var(--green)" /></td><td style={{ fontWeight: 800 }}>{(f.score_total ?? 0).toFixed(1)}</td></tr>))}</tbody></table></div></div>);}// ── Nhật ký từng phiên của một người ───────────────────────────function UserSessions({ detail }) {
backend/app/services/analytics/etl.py+45
backend/tests/test_analytics.py+40
frontend/src/components/admin/UsageDashboard.jsx+98-1