Files
lang/materials/build_dashboard.py
T

446 lines
17 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""从 me/*.md 派生 SQLite 镜像 (me/lang.db) 并渲染仪表盘 (me/dashboard.html)。
用法:
python materials/build_dashboard.py
事实来源仍是 me/*.md(大模型只写 Markdown 表)。本脚本负责:
1. 解析 me/ 下的 Markdown 表 → 写入 me/lang.db(SQLite,可查询)
2. 渲染 me/dashboard.html(自包含,无需联网)
"""
from __future__ import annotations
import datetime as _dt
import json
import re
import sqlite3
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
ME = ROOT / "me"
DB = ME / "lang.db"
OUT = ME / "dashboard.html"
# ---------- Markdown 表解析 ----------
def read(name: str) -> str:
p = ME / name
return p.read_text(encoding="utf-8") if p.exists() else ""
def parse_tables(text: str) -> list[tuple[list[str], list[list[str]]]]:
"""返回 [(header, rows), ...],按出现顺序。"""
blocks: list[list[list[str]]] = []
cur: list[list[str]] = []
for ln in text.splitlines():
s = ln.strip()
if s.startswith("|") and s.endswith("|"):
cur.append([c.strip() for c in s.strip("|").split("|")])
elif cur:
blocks.append(cur)
cur = []
if cur:
blocks.append(cur)
out: list[tuple[list[str], list[list[str]]]] = []
for b in blocks:
if len(b) < 2:
continue
header = b[0]
rows = [
r for r in b[1:]
if not all(set(c) <= set("-: ") for c in r) # 跳过 |---|---| 分隔行
]
out.append((header, rows))
return out
def to_dicts(header: list[str], rows: list[list[str]]) -> list[dict[str, str]]:
result = []
for r in rows:
d = {h: (r[i] if i < len(r) else "") for i, h in enumerate(header)}
result.append(d)
return result
def cefr(cell: str) -> str:
m = re.search(r"[ABC][12]\+?", cell or "")
return m.group(0) if m else (cell or "").strip()
# ---------- 抽取 me/ 数据 ----------
def load_items() -> list[dict]:
items = []
for kind, fname in (
("word", "word-bank.md"),
("phrase", "phrase-bank.md"),
("expression", "expression-bank.md"),
):
tables = parse_tables(read(fname))
if not tables:
continue
header, rows = tables[0]
for d in to_dicts(header, rows):
if not d.get("id"):
continue
items.append({
"id": d.get("id", ""),
"kind": kind,
"item": d.get("item", ""),
"level": d.get("level", ""),
"meaning": d.get("meaning", ""),
"context": d.get("context", ""),
"status": d.get("status", ""),
"first": d.get("first", ""),
"fix": d.get("fix", ""),
"function": d.get("function", ""),
"tags": d.get("tags", ""),
"source": d.get("source", ""),
"added": d.get("added", ""),
"hits": int(d.get("hits") or 0),
"streak": int(d.get("streak") or 0),
"next_review": d.get("next_review", ""),
})
return items
def load_grammar() -> list[dict]:
tables = parse_tables(read("grammar-fixes.md"))
if not tables:
return []
header, rows = tables[0]
out = []
for d in to_dicts(header, rows):
if not d.get("id"):
continue
out.append({
"id": d.get("id", ""),
"category": d.get("category", ""),
"issue": d.get("issue", ""),
"rule": d.get("rule", ""),
"examples": d.get("examples", ""),
"status": d.get("status", ""),
"count": int(d.get("count") or 0),
"first": d.get("first", ""),
"last": d.get("last", ""),
"next_review": d.get("next_review", ""),
})
return out
def load_profile() -> tuple[list[dict], list[dict], list[dict]]:
text = read("profile.md")
tables = parse_tables(text)
skills, log = [], []
if tables:
h, rows = tables[0]
for d in to_dicts(h, rows):
name = d.get("技能", "")
if not name:
continue
key = ("reading" if "读" in name else
"listening" if "听" in name else
"speaking" if "说" in name else
"writing" if "写" in name else name)
skills.append({
"id": key,
"name": name,
"level": cefr(d.get("表现等级", "")),
"confidence": d.get("置信度", ""),
"note": d.get("依据 / 备注", d.get("备注", "")),
})
if len(tables) > 1:
h, rows = tables[1]
for d in to_dicts(h, rows):
if not d.get("日期"):
continue
log.append({
"date": d.get("日期", ""),
"type": d.get("类型", ""),
"material": d.get("材料等级", ""),
"listening": d.get("听", ""),
"speaking": d.get("说", ""),
"reading": d.get("读", ""),
"writing": d.get("写", ""),
"note": d.get("备注", ""),
})
history = []
for ln in text.splitlines():
m = re.match(r"^-\s*`?(\d{4}-\d{2}-\d{2})`?\s*(.*)$", ln.strip())
if m:
history.append({"date": m.group(1), "text": m.group(2).strip()})
return skills, log, history
# ---------- SQLite ----------
def build_db(items, grammar, skills, log, history) -> None:
conn = sqlite3.connect(DB)
conn.executescript("""
DROP TABLE IF EXISTS items;
DROP TABLE IF EXISTS grammar_fixes;
DROP TABLE IF EXISTS skills;
DROP TABLE IF EXISTS training_log;
DROP TABLE IF EXISTS level_history;
CREATE TABLE items (
id TEXT PRIMARY KEY, kind TEXT NOT NULL, item TEXT, level TEXT,
meaning TEXT, context TEXT, status TEXT, first TEXT, fix TEXT,
function TEXT, tags TEXT, source TEXT, added TEXT,
hits INTEGER DEFAULT 0, streak INTEGER DEFAULT 0, next_review TEXT
);
CREATE TABLE grammar_fixes (
id TEXT PRIMARY KEY, category TEXT, issue TEXT, rule TEXT, examples TEXT,
status TEXT, count INTEGER DEFAULT 0, first TEXT, last TEXT, next_review TEXT
);
CREATE TABLE skills (
id TEXT PRIMARY KEY, name TEXT, level TEXT, confidence TEXT, note TEXT
);
CREATE TABLE training_log (
id INTEGER PRIMARY KEY AUTOINCREMENT, date TEXT, type TEXT, material_level TEXT,
listening TEXT, speaking TEXT, reading TEXT, writing TEXT, note TEXT
);
CREATE TABLE level_history (
id INTEGER PRIMARY KEY AUTOINCREMENT, date TEXT, text TEXT
);
""")
conn.executemany(
"INSERT OR REPLACE INTO items VALUES (:id,:kind,:item,:level,:meaning,:context,"
":status,:first,:fix,:function,:tags,:source,:added,:hits,:streak,:next_review)",
items)
conn.executemany(
"INSERT OR REPLACE INTO grammar_fixes VALUES (:id,:category,:issue,:rule,:examples,"
":status,:count,:first,:last,:next_review)", grammar)
conn.executemany(
"INSERT OR REPLACE INTO skills VALUES (:id,:name,:level,:confidence,:note)", skills)
conn.executemany(
"INSERT INTO training_log (date,type,material_level,listening,speaking,reading,writing,note)"
" VALUES (:date,:type,:material,:listening,:speaking,:reading,:writing,:note)", log)
conn.executemany(
"INSERT INTO level_history (date,text) VALUES (:date,:text)", history)
conn.commit()
conn.close()
def overview(items, grammar) -> dict:
def counts(rows):
c = {"known": 0, "learning": 0, "fix": 0}
for r in rows:
if r["status"] in c:
c[r["status"]] += 1
return c
word = [i for i in items if i["kind"] == "word"]
phrase = [i for i in items if i["kind"] == "phrase"]
expr = [i for i in items if i["kind"] == "expression"]
return {
"word": {**counts(word), "total": len(word)},
"phrase": {**counts(phrase), "total": len(phrase)},
"expression": {**counts(expr), "total": len(expr)},
"grammar": {"fix": sum(1 for g in grammar if g["status"] == "fix"),
"known": sum(1 for g in grammar if g["status"] == "known"),
"total": len(grammar)},
}
# ---------- HTML ----------
HTML = r"""<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Lang · 我的学习状态</title>
<style>
:root{
--bg:#0f1115; --panel:#171a21; --panel2:#1e222b; --line:#2a2f3a;
--fg:#e7e9ee; --muted:#9aa3b2; --accent:#5b8def;
--known:#2ecc71; --learning:#f1c40f; --fix:#e74c3c;
}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--fg);
font:15px/1.55 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"PingFang SC","Microsoft YaHei",sans-serif}
header{padding:22px 26px;border-bottom:1px solid var(--line);display:flex;
justify-content:space-between;align-items:baseline;flex-wrap:wrap;gap:8px}
h1{margin:0;font-size:20px;letter-spacing:.3px}
.gen{color:var(--muted);font-size:13px}
main{padding:22px 26px;max-width:1200px;margin:0 auto}
h2{font-size:15px;text-transform:uppercase;letter-spacing:.8px;color:var(--muted);
margin:30px 0 12px;font-weight:600}
.cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:12px}
.card{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:16px}
.card .k{color:var(--muted);font-size:13px}
.card .v{font-size:28px;font-weight:700;margin-top:4px}
.card .c{color:var(--muted);font-size:12px;margin-top:6px}
table{width:100%;border-collapse:collapse;background:var(--panel);
border:1px solid var(--line);border-radius:10px;overflow:hidden;font-size:13.5px}
th,td{padding:9px 11px;text-align:left;border-bottom:1px solid var(--line);vertical-align:top}
th{background:var(--panel2);color:var(--muted);font-weight:600;position:sticky;top:0}
tr:last-child td{border-bottom:none}
code,.mono{font-family:ui-monospace,SFMono-Regular,Consolas,monospace;font-size:12.5px;color:#c9d1e2}
.badge{display:inline-block;padding:1px 8px;border-radius:999px;font-size:12px;font-weight:600}
.b-known{background:rgba(46,204,113,.15);color:var(--known)}
.b-learning{background:rgba(241,196,15,.15);color:var(--learning)}
.b-fix{background:rgba(231,76,60,.15);color:var(--fix)}
.fx{color:#ffb4a8}
.toolbar{display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin-bottom:10px}
.toolbar button,.toolbar input{background:var(--panel2);color:var(--fg);
border:1px solid var(--line);border-radius:8px;padding:6px 11px;font-size:13px;cursor:pointer}
.toolbar button.on{border-color:var(--accent);color:#fff;background:#24314d}
.toolbar input{cursor:text;min-width:200px}
.muted{color:var(--muted)}
.wrap{overflow:auto;max-height:70vh;border-radius:10px}
footer{color:var(--muted);padding:30px 26px;font-size:12px;text-align:center}
</style>
</head>
<body>
<header>
<h1>Lang · 我的学习状态</h1>
<span class="gen">生成于 __GENERATED__ · 数据源 me/*.md</span>
</header>
<main>
<h2>四维等级</h2>
<div class="cards" id="skills"></div>
<h2>掌握概览</h2>
<div class="cards" id="overview"></div>
<h2>单词 / 词组 / 表达</h2>
<div class="toolbar">
<button data-f="all" class="on">全部</button>
<button data-f="known">已掌握</button>
<button data-f="learning">学习中</button>
<button data-f="fix">待修正</button>
<input id="q" placeholder="搜索 item / 释义 / 上下文…">
</div>
<div class="wrap"><table id="items"></table></div>
<h2>语法修正</h2>
<div class="wrap"><table id="grammar"></table></div>
<h2>训练日志</h2>
<div class="wrap"><table id="log"></table></div>
<h2>等级变更历史</h2>
<div class="wrap"><table id="history"></table></div>
</main>
<footer>由 materials/build_dashboard.py 生成 · SQLite: me/lang.db</footer>
<script>
const DATA = __DATA__;
const esc = s => String(s ?? "").replace(/[&<>"]/g, c => ({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"}[c]));
const badge = s => s ? `<span class="badge b-${s}">${s}</span>` : "";
const fx = s => s ? `<span class="fx mono">${esc(s)}</span>` : "";
// 四维等级
document.getElementById("skills").innerHTML = DATA.skills.map(s => `
<div class="card"><div class="k">${esc(s.name)}</div>
<div class="v">${esc(s.level)||"—"}</div>
<div class="c">置信度 ${esc(s.confidence)||"—"}</div></div>`).join("")
|| `<div class="muted">无数据</div>`;
// 概览
const ov = DATA.overview;
const glyph = {word:"单词", phrase:"词组", expression:"表达", grammar:"语法"};
document.getElementById("overview").innerHTML = Object.keys(glyph).map(k => {
const o = ov[k];
const parts = k === "grammar"
? `待修正 ${o.fix} · 已克服 ${o.known||0}`
: `已掌握 ${o.known} · 学习中 ${o.learning} · 待修正 ${o.fix}`;
return `<div class="card"><div class="k">${glyph[k]}</div>
<div class="v">${o.total}</div><div class="c">${parts}</div></div>`;
}).join("");
// 词条表 + 过滤
const KIND = {word:"单词", phrase:"词组", expression:"表达"};
function renderItems() {
const f = currentFilter, q = document.getElementById("q").value.trim().toLowerCase();
const rows = DATA.items.filter(i =>
(f === "all" || i.status === f) &&
(!q || (i.item + i.meaning + i.context + i.tags).toLowerCase().includes(q)));
document.getElementById("items").innerHTML =
`<thead><tr><th>id</th><th>类型</th><th>条目</th><th>等级</th><th>释义</th>
<th>上下文</th><th>状态</th><th>first</th><th>修正</th><th>标签</th></tr></thead><tbody>` +
rows.map(i => `<tr>
<td class="mono">${esc(i.id)}</td><td>${KIND[i.kind]||i.kind}</td>
<td><b>${esc(i.item)}</b></td><td>${esc(i.level)}</td>
<td>${esc(i.meaning)}</td><td class="muted">${esc(i.context)}</td>
<td>${badge(i.status)}</td><td class="mono">${esc(i.first)}</td>
<td>${fx(i.fix)}</td><td class="muted">${esc(i.tags)}</td></tr>`).join("") +
`</tbody>`;
}
let currentFilter = "all";
document.querySelectorAll(".toolbar button[data-f]").forEach(b => b.onclick = () => {
currentFilter = b.dataset.f;
document.querySelectorAll(".toolbar button[data-f]").forEach(x => x.classList.toggle("on", x === b));
renderItems();
});
document.getElementById("q").oninput = renderItems;
// 语法
document.getElementById("grammar").innerHTML =
`<thead><tr><th>id</th><th>类别</th><th>问题</th><th>正确规则</th><th>例子</th>
<th>状态</th><th>次数</th><th>最近</th><th>下次复习</th></tr></thead><tbody>` +
(DATA.grammar.map(g => `<tr>
<td class="mono">${esc(g.id)}</td><td>${esc(g.category)}</td>
<td>${esc(g.issue)}</td><td class="muted">${esc(g.rule)}</td>
<td>${fx(g.examples)}</td><td>${badge(g.status === "known" ? "known" : g.status)}</td>
<td>${g.count}</td><td class="mono">${esc(g.last)}</td>
<td class="mono">${esc(g.next_review)}</td></tr>`).join("") || "") + `</tbody>`;
// 训练日志
document.getElementById("log").innerHTML =
`<thead><tr><th>日期</th><th>类型</th><th>材料</th><th>听</th><th>说</th><th>读</th><th>写</th><th>备注</th></tr></thead><tbody>` +
(DATA.log.map(l => `<tr><td class="mono">${esc(l.date)}</td><td>${esc(l.type)}</td>
<td>${esc(l.material)}</td><td>${esc(l.listening)}</td><td>${esc(l.speaking)}</td>
<td>${esc(l.reading)}</td><td>${esc(l.writing)}</td>
<td class="muted">${esc(l.note)}</td></tr>`).join("") || "") + `</tbody>`;
// 等级历史
document.getElementById("history").innerHTML =
`<thead><tr><th>日期</th><th>变更</th></tr></thead><tbody>` +
(DATA.history.map(h => `<tr><td class="mono">${esc(h.date)}</td>
<td>${esc(h.text)}</td></tr>`).join("") || "") + `</tbody>`;
renderItems();
</script>
</body>
</html>
"""
def build_html(payload: dict) -> None:
data_json = json.dumps(payload, ensure_ascii=False)
html = (HTML
.replace("__GENERATED__", payload["generated"])
.replace("__DATA__", data_json))
OUT.write_text(html, encoding="utf-8")
def main() -> None:
items = load_items()
grammar = load_grammar()
skills, log, history = load_profile()
build_db(items, grammar, skills, log, history)
payload = {
"generated": _dt.datetime.now().strftime("%Y-%m-%d %H:%M"),
"skills": skills,
"overview": overview(items, grammar),
"items": items,
"grammar": grammar,
"log": log,
"history": history,
}
build_html(payload)
print(f"DB : {DB.relative_to(ROOT)} "
f"({len(items)} items, {len(grammar)} grammar)")
print(f"HTML : {OUT.relative_to(ROOT)}")
if __name__ == "__main__":
sys.exit(main())