SCUT-SS / space /index.html
NoahIsARider's picture
SCUT-SS: 华南理工软件学院课程复习资料,113 页 / 2427 片段 / 9 门课,非课程分支已剔除
1d8c46a verified
Raw History Blame Contribute Delete
16 kB
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>SCUT-SS 课程资料检索 · 浏览器端 RAG</title>
<style>
:root {
--bg: #f6f7fb; --card: #ffffff; --ink: #1b2130; --muted: #6b7280;
--line: #e5e7eb; --accent: #3b5bfd; --accent-soft: #eef1ff;
--ok: #0f9d58; --warn: #b45309;
}
* { box-sizing: border-box; }
body {
margin: 0; background: var(--bg); color: var(--ink); line-height: 1.6;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
}
header { background: linear-gradient(120deg, #3b5bfd, #6d5bfd 60%, #8b5cf6); color: #fff; padding: 28px 20px 24px; }
.wrap { max-width: 980px; margin: 0 auto; padding: 0 20px; }
header h1 { margin: 0 0 6px; font-size: 22px; }
header p { margin: 0; opacity: .9; font-size: 14px; }
section { margin: 22px auto; }
.card { background: var(--card); border: 1px solid var(--line); border-radius: 14px; padding: 18px 20px; box-shadow: 0 1px 2px rgba(16,24,40,.04); }
h2 { font-size: 14px; margin: 0 0 12px; color: var(--muted); font-weight: 600; letter-spacing: .5px; }
label { font-size: 13px; color: var(--muted); display: block; margin-bottom: 4px; }
input[type="text"], input[type="password"], select {
width: 100%; padding: 10px 12px; border: 1px solid var(--line); border-radius: 10px;
font-size: 14px; background: #fff; color: var(--ink); outline: none;
}
input:focus, select:focus { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); }
.row { display: flex; gap: 12px; flex-wrap: wrap; }
.row > div { flex: 1 1 200px; }
button { border: 0; border-radius: 10px; padding: 10px 16px; font-size: 14px; cursor: pointer; background: var(--accent); color: #fff; font-weight: 600; }
button:hover { opacity: .9; }
button.ghost { background: #fff; color: var(--accent); border: 1px solid var(--accent); }
button:disabled { opacity: .5; cursor: not-allowed; }
.searchbar { display: flex; gap: 10px; }
.searchbar input { flex: 1; font-size: 15px; padding: 12px 14px; }
.chips { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 10px; }
.chip { background: var(--accent-soft); color: var(--accent); border: 0; border-radius: 999px; padding: 5px 12px; font-size: 12px; cursor: pointer; }
#status { font-size: 13px; color: var(--muted); margin-top: 10px; }
.bar { height: 6px; background: var(--line); border-radius: 999px; overflow: hidden; margin-top: 8px; }
.bar > i { display: block; height: 100%; width: 0; background: var(--accent); transition: width .2s; }
.hit { border: 1px solid var(--line); border-radius: 12px; padding: 14px 16px; margin-bottom: 12px; background: #fff; }
.hit .meta { font-size: 12px; color: var(--muted); display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }
.hit .title { font-weight: 600; font-size: 14px; margin: 4px 0 6px; }
.hit .text { font-size: 14px; white-space: pre-wrap; word-break: break-word; }
.score { background: var(--accent-soft); color: var(--accent); border-radius: 6px; padding: 1px 8px; font-weight: 600; }
a { color: var(--accent); text-decoration: none; }
a:hover { text-decoration: underline; }
.answer { background: #f8fafc; border-left: 3px solid var(--accent); padding: 14px 16px; border-radius: 0 10px 10px 0; white-space: pre-wrap; }
.err { color: var(--warn); font-size: 13px; }
.ok { color: var(--ok); font-size: 13px; }
details summary { cursor: pointer; font-size: 13px; color: var(--muted); }
footer { color: var(--muted); font-size: 12px; text-align: center; padding: 30px 20px 40px; }
.grid2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 12px; }
</style>
</head>
<body>
<header>
<div class="wrap">
<h1>📚 SCUT-SS 课程资料检索</h1>
<p>华南理工大学软件学院课程复习资料 · 检索全部在浏览器本地完成,无需本地模型</p>
</div>
</header>
<div class="wrap">
<section class="card">
<h2>数据</h2>
<div class="row">
<div>
<label>数据来源(留空则读取同目录 chunks.jsonl)</label>
<input id="src" type="text" placeholder="chunks.jsonl" value="chunks.jsonl" />
</div>
<div style="flex:0 0 auto; display:flex; align-items:flex-end;">
<button id="load">加载并建索引</button>
</div>
</div>
<div id="status">尚未加载数据。</div>
<div class="bar"><i id="bar"></i></div>
<details style="margin-top:10px">
<summary>数据源说明 / 想从 HuggingFace 数据集仓库在线拉取?</summary>
<p style="font-size:13px;color:var(--muted)">
默认读取 Space 同目录下的 <code>chunks.jsonl</code>(离线可用;Duplicate 本 Space 后自带数据)。
也可填入任意公开直链,例如
<code>https://huggingface.co/datasets/&lt;用户名&gt;/&lt;数据集&gt;/resolve/main/data/dataset/chunks.jsonl</code>。
</p>
</details>
</section>
<section class="card">
<h2>检索</h2>
<div class="searchbar">
<input id="q" type="text" placeholder="例如:黑盒测试的等价类划分怎么划?" />
<button id="go">检索</button>
</div>
<div class="chips" id="chips"></div>
<div class="row" style="margin-top:12px">
<div>
<label>课程筛选</label>
<select id="course"><option value="">全部课程</option></select>
</div>
<div style="flex:0 0 140px">
<label>返回条数</label>
<select id="k"><option>3</option><option selected>5</option><option>8</option><option>12</option></select>
</div>
</div>
</section>
<section id="results"></section>
<section class="card" id="llmCard" style="display:none">
<h2>让云端模型基于资料回答(可选)</h2>
<div class="grid2">
<div><label>Base URL</label><input id="baseUrl" type="text" placeholder="https://api.siliconflow.cn/v1" /></div>
<div><label>模型</label><input id="model" type="text" placeholder="deepseek-ai/DeepSeek-V3" /></div>
<div><label>API Key(仅保存在本机浏览器)</label><input id="apiKey" type="password" placeholder="sk-..." /></div>
</div>
<div class="row" style="margin-top:12px">
<button id="ask">向模型提问</button>
<button class="ghost" id="copyCtx">复制上下文(给 IDE / 聊天模型)</button>
</div>
<div id="llmOut" style="margin-top:12px"></div>
</section>
</div>
<footer>静态页面 · 数据来自学院共享知识库,仅供学习使用 · 检索结果请与原文核对</footer>
<script>
const $ = (id) => document.getElementById(id);
const state = { chunks: [], index: null, hits: [] };
function addGrams(s, map) {
const t = " " + String(s).replace(/\s+/g, " ") + " ";
for (let i = 0; i + 1 < t.length; i++) {
const key = t.charCodeAt(i) * 65536 + t.charCodeAt(i + 1);
map.set(key, (map.get(key) || 0) + 1);
}
}
async function buildIndex(chunks, onProgress) {
const N = chunks.length;
const dfs = new Map();
const docGrams = new Array(N);
for (let i = 0; i < N; i++) {
const m = new Map();
addGrams(chunks[i].text, m);
docGrams[i] = m;
for (const g of m.keys()) dfs.set(g, (dfs.get(g) || 0) + 1);
if (i % 400 === 0) { onProgress(i / N * 0.5); await new Promise(r => setTimeout(r, 0)); }
}
const vocab = new Map();
const dfList = [];
for (const [g, df] of dfs) if (df >= 2) { vocab.set(g, vocab.size); dfList.push(df); }
const V = vocab.size;
const idf = new Float32Array(V);
for (let j = 0; j < V; j++) idf[j] = Math.log((1 + N) / (1 + dfList[j])) + 1;
const counts = new Int32Array(V);
for (let i = 0; i < N; i++) {
for (const g of docGrams[i].keys()) { const j = vocab.get(g); if (j !== undefined) counts[j]++; }
if (i % 400 === 0) { onProgress(0.5 + i / N * 0.15); await new Promise(r => setTimeout(r, 0)); }
}
const off = new Int32Array(V + 1);
let tot = 0;
for (let j = 0; j < V; j++) { off[j] = tot; tot += counts[j]; }
off[V] = tot;
const pDoc = new Int32Array(tot);
const pVal = new Float32Array(tot);
const cursor = Int32Array.from(off.subarray(0, V));
for (let i = 0; i < N; i++) {
let norm = 0;
const idxs = [], vals = [];
for (const [g, cnt] of docGrams[i]) {
const j = vocab.get(g);
if (j === undefined) continue;
const v = (1 + Math.log(cnt)) * idf[j];
idxs.push(j); vals.push(v); norm += v * v;
}
norm = Math.sqrt(norm) || 1;
for (let t = 0; t < idxs.length; t++) { const p = cursor[idxs[t]]++; pDoc[p] = i; pVal[p] = vals[t] / norm; }
if (i % 400 === 0) { onProgress(0.65 + i / N * 0.35); await new Promise(r => setTimeout(r, 0)); }
}
return { N, vocab, idf, off, pDoc, pVal };
}
function search(index, chunks, query, k, course) {
const q = new Map();
addGrams(query, q);
const scores = new Float32Array(index.N);
let qnorm = 0;
const qv = [];
for (const [g, cnt] of q) {
const j = index.vocab.get(g);
if (j === undefined) continue;
const v = (1 + Math.log(cnt)) * index.idf[j];
qv.push([j, v]); qnorm += v * v;
}
qnorm = Math.sqrt(qnorm) || 1;
for (const [j, v] of qv) {
const val = v / qnorm;
for (let p = index.off[j]; p < index.off[j + 1]; p++) scores[index.pDoc[p]] += val * index.pVal[p];
}
const order = Array.from(scores.keys()).filter(i => scores[i] > 0);
order.sort((a, b) => scores[b] - scores[a]);
const out = [];
for (const i of order) {
if (course && !(chunks[i].course || "").includes(course) && !(chunks[i].path || "").includes(course)) continue;
out.push({ chunk: chunks[i], score: scores[i] });
if (out.length >= k) break;
}
return out;
}
function esc(s) {
return String(s).replace(/[&<>]/g, c => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;" }[c]));
}
function renderHits(hits) {
const box = $("results");
if (!hits.length) { box.innerHTML = '<div class="card">没有检索到相关内容,换个说法试试。</div>'; return; }
box.innerHTML = hits.map((h, i) => `
<div class="hit">
<div class="meta">
<span class="score">${h.score.toFixed(3)}</span>
<span>${esc(h.chunk.course || "")}</span>
${h.chunk.url ? '<a href="' + esc(h.chunk.url) + '" target="_blank" rel="noopener">原文 ↗</a>' : ""}
</div>
<div class="title">${i + 1}. ${esc(h.chunk.path || h.chunk.title)}${h.chunk.section ? " · " + esc(h.chunk.section) : ""}</div>
<div class="text">${esc(h.chunk.text)}</div>
</div>`).join("");
$("llmCard").style.display = "";
}
function contextText() {
return state.hits.map((h, i) =>
"[" + (i + 1) + "] 来源:" + h.chunk.path + (h.chunk.section ? " · " + h.chunk.section : "") +
"\nURL: " + (h.chunk.url || "") + "\n" + h.chunk.text + "\n"
).join("\n");
}
function promptText(question) {
return "你是华南理工大学软件学院的学习助手。请只依据下面提供的资料回答问题;\n" +
"资料里没有的内容请明确说明“资料中没有提到”,不要编造。回答用中文,要点式结构,关键结论后标注来源编号 [1] [2]。\n\n" +
"资料:\n" + contextText() + "\n\n问题:" + question;
}
async function load() {
const src = ($("src").value.trim() || "chunks.jsonl");
$("load").disabled = true;
$("status").textContent = "正在加载 " + src + " ...";
try {
const res = await fetch(src, { cache: "no-cache" }); // revalidate: force-cache pinned stale data
if (!res.ok) throw new Error("HTTP " + res.status);
const text = await res.text();
state.chunks = text.split("\n").filter(l => l.trim()).map(l => JSON.parse(l));
$("status").textContent = "已加载 " + state.chunks.length + " 个片段,正在建立索引 ...";
state.index = await buildIndex(state.chunks, p => { $("bar").style.width = (p * 100).toFixed(1) + "%"; });
$("bar").style.width = "100%";
const courses = [...new Set(state.chunks.map(c => c.course).filter(Boolean))].sort();
$("course").innerHTML = '<option value="">全部课程</option>' +
courses.map(c => '<option value="' + esc(c) + '">' + esc(c) + "</option>").join("");
$("status").innerHTML = '<span class="ok">就绪:' + state.chunks.length + " 个片段," + courses.length + " 个课程分类,可以开始检索。</span>";
} catch (e) {
$("status").innerHTML = '<span class="err">加载失败:' + esc(e.message) +
"。静态托管请确认 chunks.jsonl 与 index.html 在同一目录;跨域拉取请确认链接公开可访问(CORS)。</span>";
} finally {
$("load").disabled = false;
}
}
function runSearch() {
if (!state.index) { $("status").textContent = "请先加载数据。"; return; }
const q = $("q").value.trim();
if (!q) return;
state.hits = search(state.index, state.chunks, q, parseInt($("k").value, 10), $("course").value);
renderHits(state.hits);
}
async function askModel() {
const out = $("llmOut");
const key = $("apiKey").value.trim();
const base = ($("baseUrl").value.trim() || "https://api.siliconflow.cn/v1").replace(/\/+$/, "");
const model = $("model").value.trim();
if (!key || !model) { out.innerHTML = '<span class="err">请填写 API Key 与模型名。</span>'; return; }
if (!state.hits.length) { out.innerHTML = '<span class="err">请先检索。</span>'; return; }
out.innerHTML = "正在调用模型 ...";
try {
const res = await fetch(base + "/chat/completions", {
method: "POST",
headers: { "Content-Type": "application/json", "Authorization": "Bearer " + key },
body: JSON.stringify({
model: model,
messages: [
{ role: "system", content: "你是一个严谨的课程学习助手。" },
{ role: "user", content: promptText($("q").value.trim()) }
],
temperature: 0.2
})
});
if (!res.ok) throw new Error("HTTP " + res.status + " " + (await res.text()).slice(0, 200));
const data = await res.json();
out.innerHTML = '<div class="answer">' + esc(data.choices[0].message.content) + "</div>";
} catch (e) {
out.innerHTML = '<span class="err">调用失败:' + esc(e.message) +
"。多数情况是该接口未允许浏览器跨域(CORS);可用「复制上下文」把资料粘给任意聊天模型。</span>";
}
}
const EXAMPLES = ["黑盒测试有哪些方法", "ATAM 的评估步骤", "数据库事务隔离级别", "关键路径法怎么算", "历年卷:操作系统考点"];
$("chips").innerHTML = EXAMPLES.map(t => '<button class="chip">' + t + "</button>").join("");
$("chips").onclick = (e) => { if (e.target.classList.contains("chip")) { $("q").value = e.target.textContent; runSearch(); } };
$("load").onclick = load;
$("go").onclick = runSearch;
$("q").onkeydown = (e) => { if (e.key === "Enter") runSearch(); };
$("ask").onclick = askModel;
$("copyCtx").onclick = async () => {
if (!state.hits.length) { $("llmOut").innerHTML = '<span class="err">请先检索。</span>'; return; }
const text = "# 请基于以下资料回答问题\n\n**问题**:" + $("q").value.trim() + "\n\n" +
"**要求**:只依据下列资料作答;资料未覆盖请说明“资料中没有提到”;关键结论标注来源编号。\n\n## 资料\n\n" + contextText();
try {
await navigator.clipboard.writeText(text);
$("llmOut").innerHTML = '<span class="ok">已复制上下文,粘贴到任意聊天模型或 IDE 即可。</span>';
} catch (e) {
$("llmOut").innerHTML = '<span class="err">浏览器拒绝了剪贴板访问,请手动复制。</span>';
}
};
load();
</script>
</body>
</html>