新增单双周课表图片收取、本地识别校对及排班数据导出
This commit is contained in:
@@ -15,3 +15,6 @@ WORKLOG_DEV_MODE=false
|
||||
# WORKLOG_SMTP_FROM=WorkLog <notify@example.com>
|
||||
# WORKLOG_SMTP_TLS=ssl
|
||||
# WORKLOG_EMAIL_CODE_TTL_MIN=10
|
||||
|
||||
# 课表收取负责人(注册邮箱,多个用逗号分隔;留空时仅本人可查看自己的课表)
|
||||
# WORKLOG_TIMETABLE_COLLECTORS=collector@example.com
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
## 功能
|
||||
|
||||
- **课表收取**:单周、双周分别上传课表图片,每人每类只保留一份,可修改替换。本地自动识别为值班时段表,由本人核对后导出 JSON / CSV;课表仅本人及指定收取负责人可查看,其他成员只见提交状态。详见 [TIMETABLES.md](TIMETABLES.md)。
|
||||
- **赋能中心一楼**:全员可见的纯记录,不接受参加、不计入参加统计;上传 ZIP 显示进度,所有登录成员可补充材料,保留各份材料及上传人信息。自动展示照片,支持 AI 读取接口及 JSON / CSV 导出;另有每日物品清点、借出申请、负责人审批和归还。负责人暂未配置,申请保持待审批。详细规则见 [CENTER.md](CENTER.md)。
|
||||
- **邮箱换绑**:登录后在账号设置中验证新邮箱即可更换绑定地址;新邮箱须未被其他账号占用。账号及活动记录保留,当前会话保留、其他设备退出,原邮箱未使用验证码失效;后续使用新邮箱登录并接收提醒。
|
||||
- **值班提醒**:读取单双周值班 JSON,按 2026-11-06 单周周五为基准循环,北京时间前一天 18:00 汇总提醒,并在每个值班时段开始前一小时再次发送邮件;邮箱匹配、预览和部署说明见 [duty/README.md](duty/README.md)。
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# 单双周课表收取
|
||||
|
||||
登录后进入“课表收取”,或打开 `/#timetables`。活动墙也有快捷入口。
|
||||
|
||||
单周、双周分别上传一张 JPG、PNG 或 WebP 图片,单张原文件最大 10MB、2400 万像素。每个账号每种周次只保留一份当前课表,修改会替换该周的图片及识别结果,另一周不变;旧图在新记录保存成功后清理。上传显示传输进度,随后显示识别处理状态。
|
||||
|
||||
图片会转成不含 EXIF 的 PNG 保存。数据库中的 `timetables` 表以 `(user_id, week_type)` 为主键,并发提交也不会产生重复课表;首次提交时间保留,修改会更新修改时间并清除此前的核对确认。更新失败会保留上一份记录。修改表格时校验版本,其他设备已经修改或替换后需要重新打开,避免覆盖新内容。
|
||||
|
||||
## 自动整理与核对
|
||||
|
||||
安装 `requirements.txt`(新增 RapidOCR 及 ONNX Runtime)即可在服务器本地识别图片,不需要外部识别服务账号,也不发送课表到外部平台。采用 RapidOCR 3.10 系列默认附带的中文模型,首次识别加载模型会比后续慢;普通 CPU 即可运行,每次识别最多使用两个推理线程,同一服务进程按顺序执行识别任务。
|
||||
|
||||
参考:[RapidOCR 使用说明](https://rapidai.github.io/RapidOCRDocs/main/en/install_usage/rapidocr/usage/)。
|
||||
|
||||
目前按已有值班安排整理周一至周五的四个时段:
|
||||
|
||||
| 时段ID | 节次 | 时间 |
|
||||
| --- | --- | --- |
|
||||
| `1-2` | 一二节 | 08:30–10:15 |
|
||||
| `3-4` | 三四节 | 10:25–12:10 |
|
||||
| `5-6` | 五六节 | 14:00–15:45 |
|
||||
| `7-8` | 七八节 | 16:00–17:45 |
|
||||
|
||||
程序根据图片中的星期列和节次或时间行定位课程文字,整理为“有课 / 空闲 / 待确认”。支持常见星期中文或英文表头,节次数字或“一二节”等标签。无法定位完整星期或节次时保留全部识别文字,并提示手动整理;夜间和周末的识别文字仍保留在 `raw_text`,不参与当前值班时段判断。
|
||||
|
||||
图片识别不能保证所有排版、合并课程块和跨节课程都能准确还原,必须对照原图核对。没有识别到文字的位置保持“待确认”,只有明确识别到“无课 / 空闲”等内容时才建议为空闲。本人可编辑每个时段的状态和课程备注,或在核对后将其余待确认设为空闲。保存草稿不会确认;只有20个时段均已明确,才能点击“核对无误并确认”。识别组件异常时仍保存图片,并提供手动整理,不返回虚假的识别成功结果。
|
||||
|
||||
这次仅收取和整理数据,不会自动修改已有值班表或发送额外邮件。
|
||||
|
||||
## 权限和负责人
|
||||
|
||||
所有登录成员可查看成员姓名、部门及单周/双周提交和核对状态。图片、课程内容和识别文字仅本人及指定的收取负责人可查看。本人只能修改自己的课表,负责人可查看和导出全部课表,但不能修改别人的课表。
|
||||
|
||||
在 `config.toml` 配置 `[timetable] collector_emails = ["负责人注册邮箱"]`,或设置 `WORKLOG_TIMETABLE_COLLECTORS`(多个邮箱逗号分隔,忽略大小写),修改后重启服务。当前负责人为空,成员仍可提交和修改自己的课表,配置负责人后即可统一收取。邮箱、手机号及授权令牌不放进收取列表或导出数据。
|
||||
|
||||
## 程序读取与导出
|
||||
|
||||
所有接口均需要 `Authorization: Bearer <登录会话令牌>`。
|
||||
|
||||
| 接口 | 用途 |
|
||||
| --- | --- |
|
||||
| `GET /api/timetables` | 本人课表、全员提交状态及收取概览;支持 `q` 和 `status=all/complete/incomplete/missing` |
|
||||
| `PUT /api/timetables/me/{week}?filename=课表.png` | 以图片原始字节提交或替换本人课表,`week=odd/even` |
|
||||
| `PATCH /api/timetables/me/{week}` | 提交 `revision`、完整20个 `cells` 和 `confirm`,保存本人校对结果 |
|
||||
| `GET /api/timetables/{user_id}/{week}` | 课表结构及原图引用,仅本人或收取负责人可用 |
|
||||
| `GET /api/timetables/{user_id}/{week}/file` | 读取原图;`download=true` 下载 PNG 文件 |
|
||||
| `GET /api/timetables/schema` | 周次、时段、状态、权限及可值班规则说明 |
|
||||
| `GET /api/timetables/export?format=json` | 完整结构,适合程序和AI读取 |
|
||||
| `GET /api/timetables/export?format=csv` | 每个课表20行,便于表格整理 |
|
||||
|
||||
默认 `confirmed_only=true`,只导出已核对课表;传 `false` 可包含草稿。成员导出自己,收取负责人导出所有成员。JSON 中 `structure.cells` 每项包含 `day=1..5`、`slot`、`status=busy/free/unknown`、`courses`、`confidence`、`source` 和 `eligible`。时段时间见顶层 `slots`,记录的 `week_type` 为 `odd` / `even`。时间戳为 Unix 毫秒。
|
||||
|
||||
**排班时必须使用 `eligible=true` 的时段**,即课表已确认且该时段明确为空闲;没有上传、未核对、未知时段都不能视为有空。JSON 包含核对时间及整理结果,不以原图下载链接的可访问性判断空闲。CSV 为 UTF-8 BOM,保护可能被电子表格当作公式的文本内容。
|
||||
|
||||
## 部署和备份
|
||||
|
||||
服务启动自动创建新表,不清空其他业务数据。图片保存在业务数据库同目录的 `timetables/`,应随整个 data 目录一起持久化和备份;仅数据库定时备份不包含图片。Docker 重建镜像时会安装识别依赖,继续沿用原 data 持久卷。现有材料 ZIP 和一楼活动保持原有存储方式,尚未接入百度网盘。
|
||||
@@ -45,3 +45,7 @@ code_ttl_min = 10
|
||||
[center]
|
||||
# 物品借出负责人:填写已注册账号邮箱;留空时申请保持待审批,无人可批准。
|
||||
approver_emails = []
|
||||
|
||||
[timetable]
|
||||
# 课表收取负责人:填写注册邮箱;可查阅和导出全部课表,不能修改他人课表。
|
||||
collector_emails = []
|
||||
|
||||
Vendored
+25
@@ -601,6 +601,31 @@ button:focus-visible, a:focus-visible, [tabindex]:focus-visible { outline: 3px s
|
||||
.center-tabs { max-width:500px; margin-bottom:24px; }
|
||||
.center-check-status { padding:18px 20px; background:var(--primary-soft); border:1px solid #d5e5da; border-radius:12px; margin-bottom:20px; }
|
||||
.center-subhead { margin-top:32px; }
|
||||
.timetable-mine { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:18px; margin:24px 0; }
|
||||
.timetable-card { min-width:0; padding:22px; background:var(--card); border:1px solid var(--line); border-radius:12px; }
|
||||
.timetable-card h3 { margin:0 0 12px; }
|
||||
.timetable-card p { overflow-wrap:anywhere; }
|
||||
.timetable-card .form-actions { justify-content:flex-start; flex-wrap:wrap; }
|
||||
.timetable-member { display:flex; justify-content:space-between; align-items:center; gap:16px; padding:18px 22px; }
|
||||
.timetable-member .acard-actions { flex-wrap:wrap; }
|
||||
.timetable-editor { max-width:1100px; width:100%; }
|
||||
.timetable-source { max-height:50vh; overflow:auto; margin:16px 0; border:1px solid var(--line); border-radius:8px; }
|
||||
.timetable-source img { display:block; width:100%; height:auto; }
|
||||
.timetable-grid-wrap { overflow-x:auto; margin:16px 0; }
|
||||
.timetable-grid { border-collapse:collapse; width:100%; min-width:680px; font-size:13px; }
|
||||
.timetable-grid th,.timetable-grid td { border:1px solid var(--line); padding:10px; vertical-align:top; }
|
||||
.timetable-grid th { background:var(--primary-soft); }
|
||||
.timetable-grid td { min-width:110px; }
|
||||
.timetable-grid td[data-status=unknown] { background:#fff7e7; }
|
||||
.timetable-grid td[data-status=busy] { background:#f0f4f6; }
|
||||
.timetable-grid td[data-status=free] { background:var(--primary-soft); }
|
||||
.timetable-grid textarea { margin-top:6px; font-size:12px; min-width:0; }
|
||||
.timetable-editor .form-actions { flex-wrap:wrap; }
|
||||
#timetables-view .center-export .checkline { flex-direction:row; align-items:center; align-self:center; margin:0; }
|
||||
#timetable-confirmed-only { min-width:18px; min-height:18px; width:18px; height:18px; flex:0 0 18px; padding:0; }
|
||||
.timetable-warnings { padding:12px 14px; background:#fff7e7; border-radius:8px; font-size:13px; }
|
||||
.timetable-text { white-space:pre-wrap; overflow-wrap:anywhere; max-height:220px; overflow:auto; }
|
||||
@media (max-width:600px) { .timetable-mine { grid-template-columns:1fr; } .timetable-member { flex-wrap:wrap; } .timetable-member .acard-actions { width:100%; } }
|
||||
.center-history { margin-top:28px; }
|
||||
.center-history summary { cursor:pointer; padding:12px 0; }
|
||||
.center-history .acard { margin-top:12px; }
|
||||
|
||||
Vendored
+16
-3
@@ -5,7 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>WorkLog · 活动记录</title>
|
||||
<meta name="theme-color" content="#f5f7f5" />
|
||||
<link rel="stylesheet" href="/assets/styles.css?v=19" />
|
||||
<link rel="stylesheet" href="/assets/styles.css?v=20" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="app">
|
||||
@@ -17,6 +17,7 @@
|
||||
<a href="#" data-view="feed">活动墙</a>
|
||||
<a href="#" data-view="mine">我的记录</a>
|
||||
<a href="#" data-view="center">赋能中心一楼</a>
|
||||
<a href="#timetables" data-view="timetables">课表收取</a>
|
||||
<a href="#" data-view="members">成员</a>
|
||||
<a href="#" data-view="profile">设置</a>
|
||||
</nav>
|
||||
@@ -117,7 +118,7 @@
|
||||
</div>
|
||||
<section class="center-shortcuts" aria-label="赋能中心一楼快捷入口">
|
||||
<div><strong>赋能中心一楼</strong><p>上传活动照片,完成每日清点,申请物品借用</p></div>
|
||||
<div class="center-shortcut-actions"><a class="btn primary" href="#center-records">一楼活动记录</a><a class="btn" href="#center-assets">物品清点与借出</a></div>
|
||||
<div class="center-shortcut-actions"><a class="btn primary" href="#center-records">一楼活动记录</a><a class="btn" href="#center-assets">物品清点与借出</a><a class="btn" href="#timetables">课表收取</a></div>
|
||||
</section>
|
||||
<div class="filters">
|
||||
<input id="feed-q" aria-label="搜索活动或地点" placeholder="搜索活动 / 地点" type="search" />
|
||||
@@ -175,6 +176,18 @@
|
||||
</section>
|
||||
</div>
|
||||
</main>
|
||||
<main id="timetables-view" class="view hidden">
|
||||
<div class="container">
|
||||
<div class="page-head"><div><h2>课表收取</h2><p class="muted">单周、双周分别提交,每类只保留一份,后续可修改替换。</p></div></div>
|
||||
<p class="muted">上传课表图片后自动整理为值班时段表,请对照原图核对。课表仅本人及收取负责人可查看,其他成员只看到提交状态。</p>
|
||||
<p class="muted" id="timetable-collector-note"></p>
|
||||
<div id="timetable-mine" class="timetable-mine"></div>
|
||||
<div class="page-head center-subhead"><div><h3>收取进度</h3><p class="muted" id="timetable-summary" role="status"></p></div></div>
|
||||
<div class="filters center-toolbar"><input id="timetable-q" type="search" aria-label="搜索课表成员" placeholder="搜索姓名 / 部门" /><select id="timetable-filter" aria-label="课表提交状态"><option value="all">全部成员</option><option value="complete">单双周已交齐</option><option value="incomplete">尚未交齐</option><option value="missing">均未提交</option></select><button id="timetable-refresh" class="btn">刷新</button></div>
|
||||
<div id="timetable-members" class="card-list"></div>
|
||||
<details class="center-export center-subhead"><summary>导出排班数据</summary><p class="muted" id="timetable-export-note"></p><div class="filters"><label>格式<select id="timetable-export-format"><option value="json">JSON</option><option value="csv">CSV</option></select></label><label class="checkline"><input id="timetable-confirmed-only" type="checkbox" checked /> 仅导出已核对课表</label><button id="timetable-export" class="btn primary">下载数据</button></div><p class="muted" id="timetable-export-status" role="status"></p></details>
|
||||
</div>
|
||||
</main>
|
||||
<main id="mine-view" class="view hidden">
|
||||
<div class="container">
|
||||
<div class="page-head">
|
||||
@@ -309,7 +322,7 @@
|
||||
|
||||
<div id="toast" class="toast hidden" role="status" aria-live="polite"></div>
|
||||
|
||||
<script src="/js/app.js?v=27"></script>
|
||||
<script src="/js/app.js?v=28"></script>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Vendored
+162
-7
@@ -121,7 +121,7 @@
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------- 视图切换
|
||||
const VIEWS = ["auth", "feed", "mine", "members", "user", "profile", "center"];
|
||||
const VIEWS = ["auth", "feed", "mine", "members", "user", "profile", "center", "timetables"];
|
||||
function show(view) {
|
||||
state.view = view;
|
||||
VIEWS.forEach((v) => $(`#${v}-view`).classList.toggle("hidden", v !== view));
|
||||
@@ -139,6 +139,12 @@
|
||||
if (view === "members") loadMembers();
|
||||
if (view === "profile") fillProfile();
|
||||
if (view === "center") loadCenter();
|
||||
if (view === 'timetables') { history.replaceState(null, '', '#timetables'); loadTimetables(); }
|
||||
else if (view !== 'auth' && location.hash === '#timetables') history.replaceState(null, '', location.pathname + location.search);
|
||||
if (view === 'auth') {
|
||||
$('#timetable-mine').replaceChildren(); $('#timetable-members').replaceChildren();
|
||||
timetableData = null; timetableRequest++;
|
||||
}
|
||||
}
|
||||
const showAuth = () => show("auth");
|
||||
|
||||
@@ -786,7 +792,9 @@
|
||||
$("#user-back").addEventListener("click", () => show("members"));
|
||||
|
||||
// ------------------------------------------------------------- 弹层
|
||||
let modalCleanup = null;
|
||||
function modal(html) {
|
||||
if (modalCleanup) { modalCleanup(); modalCleanup = null; }
|
||||
$("#modal-root").innerHTML = `<div class="modal-mask"><div class="modal">${html}</div></div>`;
|
||||
const mask = $("#modal-root .modal-mask");
|
||||
mask.addEventListener("click", (e) => { if (e.target === mask) closeModal(); });
|
||||
@@ -797,24 +805,29 @@
|
||||
let materialUpload = null;
|
||||
const closeModal = () => {
|
||||
if (materialUpload) materialUpload.abort();
|
||||
if (modalCleanup) { modalCleanup(); modalCleanup = null; }
|
||||
$("#modal-root").innerHTML = ""; document.removeEventListener("keydown", escListener);
|
||||
};
|
||||
|
||||
function uploadMaterial(file, onProgress) {
|
||||
return uploadFile('/api/center/materials', 'POST', file, onProgress, 'application/zip');
|
||||
}
|
||||
|
||||
function uploadFile(path, method, file, onProgress, contentType) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const xhr = new XMLHttpRequest();
|
||||
materialUpload = xhr;
|
||||
xhr.open('POST', '/api/center/materials');
|
||||
xhr.open(method, path);
|
||||
xhr.setRequestHeader('Authorization', `Bearer ${getToken()}`);
|
||||
xhr.setRequestHeader('Content-Type', 'application/zip');
|
||||
xhr.setRequestHeader('Content-Type', contentType);
|
||||
xhr.timeout = 10 * 60 * 1000;
|
||||
xhr.upload.onprogress = event => onProgress(event.loaded, event.lengthComputable ? event.total : file.size);
|
||||
xhr.upload.onload = () => onProgress(file.size, file.size);
|
||||
xhr.onload = () => {
|
||||
let result;
|
||||
try { result = JSON.parse(xhr.responseText); } catch { result = {}; }
|
||||
if (xhr.status >= 200 && xhr.status < 300 && result.id) resolve(result);
|
||||
else reject(new Error(xhr.status === 413 ? '材料包过大,请提交30MB以内的ZIP' : apiErrorMessage(result.detail, xhr.status)));
|
||||
if (xhr.status >= 200 && xhr.status < 300 && (result.id || result.timetable)) resolve(result);
|
||||
else reject(new Error(xhr.status === 413 ? (contentType === 'application/zip' ? '材料包过大,请提交30MB以内的ZIP' : '课表图片最大10MB') : apiErrorMessage(result.detail, xhr.status)));
|
||||
};
|
||||
xhr.onerror = () => reject(new Error('上传失败,请检查网络后重试'));
|
||||
xhr.ontimeout = () => reject(new Error('上传超时,请重试'));
|
||||
@@ -830,11 +843,11 @@
|
||||
return packages.length ? `<div class="activity-materials">${packages.map((item, i) => `<div><button class="btn sm" data-material="${esc(item.id)}">下载材料 ZIP${packages.length > 1 ? ` ${i + 1}` : ''}</button>${item.uploader_name ? `<span class="muted">${esc(item.uploader_name)} · ${fmtDate(item.created_at)}</span>` : ''}</div>`).join('')}</div>` : '';
|
||||
}
|
||||
|
||||
function renderUploadProgress(label, meter, loaded, total) {
|
||||
function renderUploadProgress(label, meter, loaded, total, processing = '上传完成,正在校验材料并处理照片…') {
|
||||
const percent = total ? Math.min(100, Math.floor(loaded / total * 100)) : 0;
|
||||
if (loaded >= total && total > 0) {
|
||||
meter.removeAttribute('value');
|
||||
label.textContent = '上传完成,正在校验材料并处理照片…';
|
||||
label.textContent = processing;
|
||||
} else {
|
||||
meter.value = percent;
|
||||
const size = bytes => (bytes / 1024 / 1024).toFixed(1) + ' MB';
|
||||
@@ -1134,6 +1147,147 @@
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- 课表收取
|
||||
let timetableData = null;
|
||||
let timetableRequest = 0;
|
||||
const weekLabel = week => week === 'odd' ? '单周' : '双周';
|
||||
const timetableState = item => !item ? '未提交' : item.confirmed_at ? '已核对' : '待核对';
|
||||
|
||||
async function loadTimetables() {
|
||||
const version = ++timetableRequest;
|
||||
try {
|
||||
const params = new URLSearchParams({ q: $('#timetable-q').value, status: $('#timetable-filter').value });
|
||||
const data = await api('/timetables?' + params);
|
||||
if (version !== timetableRequest) return;
|
||||
timetableData = data;
|
||||
$('#timetable-collector-note').textContent = data.collector_configured ? '' : '收取负责人暂未设置,已提交课表会保留,稍后可统一收取。';
|
||||
$('#timetable-mine').innerHTML = ['odd', 'even'].map(week => {
|
||||
const item = data.mine[week];
|
||||
return `<section class="timetable-card"><h3>我的${weekLabel(week)}课表 <span class="tag ${item?.confirmed_at ? 'attended' : 'joined'}">${timetableState(item)}</span></h3>
|
||||
<p class="muted">${item ? `${esc(item.filename)}<br />更新于 ${fmtDate(item.updated_at)}` : '上传课表截图或照片,系统自动整理为可编辑表格。'}</p>
|
||||
<div class="form-actions"><button class="btn ${item ? '' : 'primary'}" data-timetable-upload="${week}">${item ? '修改图片' : '上传课表'}</button>${item ? `<button class="btn primary" data-timetable-view="${week}" data-user-id="${state.me.id}">查看与校对</button>` : ''}</div></section>`;
|
||||
}).join('');
|
||||
const summary = data.summary;
|
||||
$('#timetable-summary').textContent = `共 ${summary.total} 人 · 已交齐 ${summary.complete} 人 · 已交一份 ${summary.partial} 人 · 均未提交 ${summary.missing} 人`;
|
||||
$('#timetable-members').innerHTML = data.members.map(person => `<article class="acard timetable-member"><div><strong>${esc(person.display_name)}</strong><p class="muted">${esc(person.department)}</p></div><div class="acard-actions">${['odd', 'even'].map(week => {
|
||||
const item = person.weeks[week];
|
||||
const label = `${weekLabel(week)}:${item.submitted ? item.confirmed ? '已核对' : '已交待核对' : '未交'}`;
|
||||
return item.submitted && person.can_read ? `<button class="btn sm" data-timetable-view="${week}" data-user-id="${person.id}">${label}</button>` : `<span class="tag ${item.submitted ? 'attended' : ''}">${label}</span>`;
|
||||
}).join('')}</div></article>`).join('') || '<div class="empty">没有符合筛选条件的成员。</div>';
|
||||
$('#timetable-export-note').textContent = (data.can_collect ? '你可以导出所有成员的课表。' : '你可以导出自己的课表;收取负责人可统一导出全部。') + '只有已核对课表中的空闲时段可列为可值班,待确认不能当作空闲。';
|
||||
} catch (error) { if (version === timetableRequest) toast(error.message, true); }
|
||||
}
|
||||
|
||||
function openTimetableUpload(week) {
|
||||
const current = timetableData?.mine[week];
|
||||
modal(`<h3>${current ? '修改' : '上传'}${weekLabel(week)}课表</h3><p class="modal-sub muted">${current ? '本次会替换原图片及识别结果,需重新核对;另一周的课表保持不变。' : '每人单周、双周各一份,后续可修改替换。'}</p>
|
||||
<form id="timetable-upload-form"><label>课表图片<input name="image" type="file" accept="image/jpeg,image/png,image/webp" required /></label><p class="muted">支持JPG、PNG、WebP,最大10MB。请保留星期和节次栏,尽量上传清晰截图。</p>
|
||||
<div id="timetable-upload-progress" class="upload-progress hidden"><p id="timetable-upload-status" role="status" aria-live="polite"></p><progress id="timetable-upload-meter" max="100" value="0" aria-labelledby="timetable-upload-status"></progress></div>
|
||||
<div class="form-error" role="alert"></div><div class="form-actions"><button class="btn" type="button" id="timetable-upload-cancel">取消</button><button class="btn primary" type="submit">上传并识别</button></div></form>`);
|
||||
const form = $('#timetable-upload-form');
|
||||
const box = $('#timetable-upload-progress'), label = $('#timetable-upload-status'), meter = $('#timetable-upload-meter');
|
||||
$('#timetable-upload-cancel').addEventListener('click', closeModal);
|
||||
form.addEventListener('submit', async event => {
|
||||
event.preventDefault();
|
||||
const button = form.querySelector('[type=submit]'), errorBox = form.querySelector('.form-error');
|
||||
if (button.disabled) return;
|
||||
const file = form.image.files[0]; errorBox.textContent = '';
|
||||
if (!file || file.size > 10 * 1024 * 1024 || !/\.(jpe?g|png|webp)$/i.test(file.name)) { errorBox.textContent = '请上传10MB以内的JPG、PNG或WebP课表图片'; return; }
|
||||
button.disabled = true; form.image.disabled = true; box.classList.remove('hidden'); button.textContent = '正在识别…';
|
||||
try {
|
||||
const response = await uploadFile('/api/timetables/me/' + week + '?filename=' + encodeURIComponent(file.name), 'PUT', file,
|
||||
(loaded, total) => renderUploadProgress(label, meter, loaded, total, '图片上传完成,正在识别并整理课表…'), file.type || 'application/octet-stream');
|
||||
if (!form.isConnected) return;
|
||||
meter.value = 100; closeModal(); toast('课表已保存,请核对识别结果'); loadTimetables();
|
||||
openTimetableEditor(response.timetable, state.me.id);
|
||||
} catch (error) {
|
||||
errorBox.textContent = error.message; label.textContent = '上传未完成,可重试。'; meter.value = 0;
|
||||
button.disabled = false; form.image.disabled = false; button.textContent = '上传并识别';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function openTimetableEditor(item, userId) {
|
||||
const editable = userId === state.me.id;
|
||||
const cells = item.structure.cells;
|
||||
const slots = timetableData.slots, days = timetableData.days;
|
||||
const statusLabels = { unknown: '待确认', busy: '有课', free: '空闲' };
|
||||
modal(`<h3>${weekLabel(item.week_type)}课表 · ${editable ? '核对与修改' : '查看'}</h3><p class="modal-sub muted">按现有四个值班时段整理周一至周五。请对照原图检查,核对后再用于排班。</p>
|
||||
<div class="timetable-source"><img id="timetable-source-image" alt="课表原图" /><p class="muted" id="timetable-image-status">正在加载原图…</p></div>
|
||||
<div class="timetable-warnings">${item.structure.warnings.map(esc).join('<br />')}</div>
|
||||
<form id="timetable-correction-form"><div class="timetable-grid-wrap"><table class="timetable-grid"><thead><tr><th scope="col">值班时段</th>${days.map(day => `<th scope="col">${esc(day)}</th>`).join('')}</tr></thead><tbody>${slots.map(slot => `<tr><th scope="row">${esc(slot.label)}<br />${slot.start}–${slot.end}</th>${days.map((_, i) => {
|
||||
const index = cells.findIndex(cell => cell.day === i+1 && cell.slot === slot.id), cell = cells[index];
|
||||
return `<td data-status="${cell.status}">${editable ? `<select aria-label="${days[i]}${slot.label}状态" data-cell="${index}">${Object.entries(statusLabels).map(([value,label]) => `<option value="${value}" ${cell.status === value ? 'selected' : ''}>${label}</option>`).join('')}</select><textarea rows="2" aria-label="${days[i]}${slot.label}课程" data-course="${index}" maxlength="500" placeholder="课程 / 备注">${esc(cell.courses)}</textarea>` : `<strong>${statusLabels[cell.status]}</strong><p>${esc(cell.courses)}</p>`}</td>`;
|
||||
}).join('')}</tr>`).join('')}</tbody></table></div>
|
||||
${editable ? '<button class="btn sm" type="button" id="timetable-fill-free">将其余待确认设为空闲</button>' : ''}
|
||||
<details><summary>图片识别文字</summary><pre class="timetable-text">${esc(item.structure.raw_text || '未识别到文字,可手动填写时段。')}</pre></details>
|
||||
<div class="form-error" role="alert"></div><p class="muted" id="timetable-confirmation-state">${item.confirmed_at ? '已核对,确认时间:' + fmtDate(item.confirmed_at) : '尚未核对,暂不能作为可值班依据。'}</p>
|
||||
<div class="form-actions"><button class="btn" type="button" id="timetable-download-image">下载原图</button><button class="btn" type="button" id="timetable-editor-close">关闭</button>${editable ? '<button class="btn" type="submit" data-confirm="false">保存草稿</button><button class="btn primary" type="submit" data-confirm="true">核对无误并确认</button>' : ''}</div></form>`);
|
||||
$('#modal-root .modal').classList.add('timetable-editor');
|
||||
const form = $('#timetable-correction-form'), img = $('#timetable-source-image'), imageStatus = $('#timetable-image-status');
|
||||
$('#timetable-editor-close').addEventListener('click', closeModal);
|
||||
$('#timetable-download-image').addEventListener('click', async event => {
|
||||
const button = event.currentTarget; button.disabled = true;
|
||||
try { await downloadCenterFile(item.image_url + '?download=true', weekLabel(item.week_type) + '课表.png'); }
|
||||
catch (error) { toast(error.message, true); }
|
||||
finally { button.disabled = false; }
|
||||
});
|
||||
let imageUrl = null;
|
||||
modalCleanup = () => { if (imageUrl) URL.revokeObjectURL(imageUrl); };
|
||||
fetch(item.image_url, { headers: { Authorization: `Bearer ${getToken()}` } }).then(async response => {
|
||||
if (!response.ok) throw new Error('原图暂不可用,请关闭后重新打开');
|
||||
const blob = await response.blob(); if (!img.isConnected) return;
|
||||
imageUrl = URL.createObjectURL(blob); img.src = imageUrl; imageStatus.textContent = '';
|
||||
}).catch(error => { imageStatus.textContent = error.message; });
|
||||
if (!editable) return;
|
||||
form.querySelectorAll('[data-cell]').forEach(select => select.addEventListener('change', () => {
|
||||
select.closest('td').dataset.status = select.value;
|
||||
form.querySelector('#timetable-confirmation-state').textContent = '有未保存修改,请重新保存并确认。';
|
||||
}));
|
||||
form.querySelectorAll('[data-course]').forEach(field => field.addEventListener('input', () => {
|
||||
form.querySelector('#timetable-confirmation-state').textContent = '有未保存修改,请重新保存并确认。';
|
||||
}));
|
||||
$('#timetable-fill-free').addEventListener('click', () => {
|
||||
form.querySelectorAll('[data-cell]').forEach(select => { if (select.value === 'unknown') { select.value = 'free'; select.dispatchEvent(new Event('change')); } });
|
||||
});
|
||||
let saving = false;
|
||||
form.addEventListener('submit', async event => {
|
||||
event.preventDefault(); if (saving) return;
|
||||
const confirm = event.submitter?.dataset.confirm === 'true';
|
||||
const edited = cells.map((cell,index) => ({ day: cell.day, slot: cell.slot, status: form.querySelector(`[data-cell="${index}"]`).value, courses: form.querySelector(`[data-course="${index}"]`).value }));
|
||||
const errorBox = form.querySelector('.form-error'); errorBox.textContent = '';
|
||||
if (confirm && edited.some(cell => cell.status === 'unknown')) { errorBox.textContent = '仍有待确认时段,请核对后再确认'; return; }
|
||||
saving = true; form.querySelectorAll('[type=submit]').forEach(button => button.disabled = true);
|
||||
try {
|
||||
await api('/timetables/me/' + item.week_type, { method: 'PATCH', body: { revision: item.revision, cells: edited, confirm } });
|
||||
closeModal(); toast(confirm ? '课表已核对确认' : '草稿已保存'); loadTimetables();
|
||||
} catch (error) { errorBox.textContent = error.message; saving = false; form.querySelectorAll('[type=submit]').forEach(button => button.disabled = false); }
|
||||
});
|
||||
}
|
||||
|
||||
for (const id of ['timetable-mine', 'timetable-members']) $('#' + id).addEventListener('click', async event => {
|
||||
const upload = event.target.closest('[data-timetable-upload]');
|
||||
if (upload) return openTimetableUpload(upload.dataset.timetableUpload);
|
||||
const view = event.target.closest('[data-timetable-view]');
|
||||
if (!view || view.disabled) return;
|
||||
view.disabled = true;
|
||||
try {
|
||||
const data = await api('/timetables/' + encodeURIComponent(view.dataset.userId) + '/' + view.dataset.timetableView);
|
||||
openTimetableEditor(data.timetable, view.dataset.userId);
|
||||
} catch (error) { toast(error.message, true); }
|
||||
finally { view.disabled = false; }
|
||||
});
|
||||
$('#timetable-q').addEventListener('input', debounce(loadTimetables, 300));
|
||||
$('#timetable-filter').addEventListener('change', loadTimetables);
|
||||
$('#timetable-refresh').addEventListener('click', loadTimetables);
|
||||
$('#timetable-export').addEventListener('click', async () => {
|
||||
const button = $('#timetable-export'); button.disabled = true;
|
||||
const format = $('#timetable-export-format').value;
|
||||
try { await downloadCenterFile('/api/timetables/export?format=' + format + '&confirmed_only=' + $('#timetable-confirmed-only').checked, 'timetables.' + format); $('#timetable-export-status').textContent = '数据已下载。'; }
|
||||
catch (error) { $('#timetable-export-status').textContent = error.message; }
|
||||
finally { button.disabled = false; }
|
||||
});
|
||||
|
||||
let centerTab = 'records';
|
||||
async function downloadCenterFile(path, fallback) {
|
||||
const response = await fetch(path, { headers: { Authorization: `Bearer ${getToken()}` } });
|
||||
@@ -1168,6 +1322,7 @@
|
||||
let centerCanReview = false;
|
||||
let centerRecords = [];
|
||||
function openCenterFromHash() {
|
||||
if (state.me && location.hash === '#timetables') { show('timetables'); return true; }
|
||||
if (!state.me || !['#center', '#center-records', '#center-assets'].includes(location.hash)) return false;
|
||||
centerTab = location.hash === '#center-assets' ? 'assets' : 'records';
|
||||
$$('[data-center-tab]').forEach(button => button.classList.toggle('active', button.dataset.centerTab === centerTab));
|
||||
|
||||
@@ -5,5 +5,7 @@ aiosqlite>=0.20,<1
|
||||
aiosmtplib>=3,<6
|
||||
pydantic>=2.7,<3
|
||||
Pillow>=11,<13
|
||||
rapidocr>=3.10,<3.11
|
||||
onnxruntime>=1.20,<2
|
||||
# 仅测试时需要
|
||||
httpx>=0.27,<1
|
||||
|
||||
@@ -42,6 +42,7 @@ from .duty import resolve_recipients
|
||||
from . import duty_receipts
|
||||
from . import center
|
||||
from . import center_export
|
||||
from . import timetables as timetable_routes
|
||||
from .models import center_activity_meta
|
||||
import json
|
||||
|
||||
@@ -687,6 +688,13 @@ def center_approvers():
|
||||
center.install(app, get_db, current_user, lambda: _db_path.parent / 'uploads', visible_clause, center_approvers)
|
||||
center_export.install(app, get_db, current_user, visible_clause)
|
||||
|
||||
def timetable_collectors():
|
||||
values = os.getenv('WORKLOG_TIMETABLE_COLLECTORS')
|
||||
emails = values.split(',') if values is not None else cfg('timetable', 'collector_emails', [])
|
||||
return {email.strip().lower() for email in emails if email.strip()}
|
||||
|
||||
timetable_routes.install(app, get_db, current_user, lambda: _db_path.parent / 'timetables', timetable_collectors)
|
||||
|
||||
|
||||
@app.exception_handler(IntegrityError)
|
||||
async def conflict_error(_request: Request, _exc: IntegrityError):
|
||||
|
||||
@@ -160,3 +160,11 @@ center_loans = Table('center_loans', metadata,
|
||||
center_checks = Table('center_checks', metadata,
|
||||
Column('day', String(10), primary_key=True), Column('user_id', String(36), ForeignKey('users.id'), nullable=False),
|
||||
Column('details', Text, nullable=False), Column('note', String(1000), nullable=False), Column('created_at', Integer, nullable=False))
|
||||
|
||||
timetables = Table('timetables', metadata,
|
||||
Column('user_id', String(36), ForeignKey('users.id', ondelete='CASCADE'), primary_key=True),
|
||||
Column('week_type', String(4), primary_key=True),
|
||||
Column('file_key', String(40), nullable=False), Column('filename', String(180), nullable=False),
|
||||
Column('structure', Text, nullable=False), Column('ocr_status', String(20), nullable=False),
|
||||
Column('created_at', Integer, nullable=False), Column('updated_at', Integer, nullable=False),
|
||||
Column('confirmed_at', Integer, nullable=True))
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
"""本地图片识别及值班时段整理。留白保持待确认,不能直接当作空闲。"""
|
||||
import io
|
||||
import re
|
||||
import threading
|
||||
import unicodedata
|
||||
from statistics import median
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
SLOTS = [
|
||||
{'id': '1-2', 'label': '一二节', 'start': '08:30', 'end': '10:15'},
|
||||
{'id': '3-4', 'label': '三四节', 'start': '10:25', 'end': '12:10'},
|
||||
{'id': '5-6', 'label': '五六节', 'start': '14:00', 'end': '15:45'},
|
||||
{'id': '7-8', 'label': '七八节', 'start': '16:00', 'end': '17:45'},
|
||||
]
|
||||
DAYS = ['周一', '周二', '周三', '周四', '周五']
|
||||
_engine = None
|
||||
_lock = threading.Lock()
|
||||
|
||||
|
||||
def blank_structure():
|
||||
return {'schema_version': 1, 'cells': [
|
||||
{'day': day, 'slot': slot['id'], 'status': 'unknown', 'courses': '', 'confidence': 0, 'source': 'ocr'}
|
||||
for slot in SLOTS for day in range(1, 6)
|
||||
], 'raw_text': '', 'warnings': []}
|
||||
|
||||
|
||||
def normalize_image(raw):
|
||||
"""验证实际图片内容并生成无EXIF的清晰PNG,拒绝多帧和超大像素图片。"""
|
||||
with Image.open(io.BytesIO(raw)) as image:
|
||||
if image.format not in ('JPEG', 'PNG', 'WEBP') or image.width * image.height > 24000000:
|
||||
raise ValueError('请上传2400万像素以内的JPG、PNG或WebP课表图片')
|
||||
if getattr(image, 'n_frames', 1) != 1:
|
||||
raise ValueError('请上传静态课表图片')
|
||||
image = ImageOps.exif_transpose(image).convert('RGB')
|
||||
output = io.BytesIO(); image.save(output, 'PNG')
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def read_image(raw):
|
||||
global _engine
|
||||
with _lock:
|
||||
if _engine is None:
|
||||
from rapidocr import RapidOCR
|
||||
_engine = RapidOCR(params={
|
||||
'Global.log_level': 'error', 'Global.max_side_len': 2400,
|
||||
'EngineConfig.onnxruntime.intra_op_num_threads': 2,
|
||||
'EngineConfig.onnxruntime.inter_op_num_threads': 1,
|
||||
})
|
||||
result = _engine(raw)
|
||||
if result.boxes is None or result.txts is None:
|
||||
return []
|
||||
return [{'box': box.tolist(), 'text': text, 'score': float(score)}
|
||||
for box, text, score in zip(result.boxes, result.txts, result.scores)]
|
||||
|
||||
|
||||
def compact(value):
|
||||
return re.sub(r'\s+', '', unicodedata.normalize('NFKC', value))
|
||||
|
||||
|
||||
def weekday(text):
|
||||
value = compact(text)
|
||||
match = re.match(r'^(?:星期|礼拜|周)([一二三四五六日天1-7])', value)
|
||||
if match:
|
||||
token = match[1]
|
||||
return int(token) if token.isdigit() else 7 if token in '日天' else '一二三四五六'.index(token) + 1
|
||||
english = {'mon': 1, 'tue': 2, 'wed': 3, 'thu': 4, 'fri': 5, 'sat': 6, 'sun': 7}
|
||||
return english.get(value.lower().strip('.')[:3]) if value.isascii() else None
|
||||
|
||||
|
||||
def periods(text):
|
||||
value = compact(text).replace('第', '').replace('节次', '').replace('节', '')
|
||||
value = value.replace('—', '-').replace('–', '-')
|
||||
chinese = {'一二': [1, 2], '三四': [3, 4], '五六': [5, 6], '七八': [7, 8]}
|
||||
if len(value) == 1 and value in '一二三四五六七八': return ['一二三四五六七八'.index(value) + 1]
|
||||
if value.replace('、', '') in chinese: return chinese[value.replace('、', '')]
|
||||
if value in chinese: return chinese[value]
|
||||
match = re.fullmatch(r'(\d{1,2})(?:[-~至、](\d{1,2}))?', value)
|
||||
if not match: return []
|
||||
start = int(match[1]); end = int(match[2] or start)
|
||||
return list(range(start, end + 1)) if 1 <= start <= end <= 12 else []
|
||||
|
||||
|
||||
def structure_from_lines(lines):
|
||||
result = blank_structure()
|
||||
result['raw_text'] = '\n'.join(line['text'] for line in lines)[:100000]
|
||||
result['warnings'] = ['识别结果需核对。未识别到文字的时段保持待确认,不自动判为空闲。']
|
||||
positioned = []
|
||||
for line in lines:
|
||||
xs = [point[0] for point in line['box']]; ys = [point[1] for point in line['box']]
|
||||
positioned.append({**line, 'x': (min(xs) + max(xs)) / 2, 'y': (min(ys) + max(ys)) / 2,
|
||||
'height': max(ys) - min(ys)})
|
||||
headers = [line for line in positioned if weekday(line['text'])]
|
||||
groups = []
|
||||
for header in headers:
|
||||
group = [line for line in headers if abs(line['y'] - header['y']) < max(15, header['height'] * 1.5)]
|
||||
groups.append(group)
|
||||
selected = max(groups, key=lambda group: len({weekday(line['text']) for line in group}), default=[])
|
||||
columns = {weekday(line['text']): line['x'] for line in selected}
|
||||
if not all(day in columns for day in range(1, 6)) or any(columns[d] >= columns[d+1] for d in range(1, 5)):
|
||||
result['warnings'].append('未能完整定位周一至周五列,请对照原图手动整理。')
|
||||
return result
|
||||
step = median(columns[d+1] - columns[d] for d in range(1, 5))
|
||||
left = columns[1] - step / 2
|
||||
header_y = median(line['y'] for line in selected)
|
||||
anchors = {slot['id']: [] for slot in SLOTS}
|
||||
for line in positioned:
|
||||
if line['x'] >= left or line['y'] <= header_y: continue
|
||||
nums = periods(line['text'])
|
||||
if nums and len(nums) <= 2:
|
||||
for index, slot in enumerate(SLOTS):
|
||||
if any(number in (index * 2 + 1, index * 2 + 2) for number in nums):
|
||||
anchors[slot['id']].append(line['y'])
|
||||
value = compact(line['text'])
|
||||
for slot in SLOTS:
|
||||
if re.match(r'^0?' + re.escape(slot['start'].lstrip('0')) + r'(?:$|[-~])', value):
|
||||
anchors[slot['id']].append(line['y'])
|
||||
if not all(anchors.values()):
|
||||
result['warnings'].append('未能完整定位一二、三四、五六、七八节,请手动核对时段。')
|
||||
return result
|
||||
centers = [median(anchors[slot['id']]) for slot in SLOTS]
|
||||
if any(centers[i] >= centers[i+1] for i in range(3)):
|
||||
result['warnings'].append('节次位置不明确,请手动整理。')
|
||||
return result
|
||||
bounds = [centers[0] - (centers[1] - centers[0]) / 2,
|
||||
*[(centers[i] + centers[i+1]) / 2 for i in range(3)],
|
||||
centers[-1] + (centers[-1] - centers[-2]) / 2]
|
||||
cells = {(cell['day'], cell['slot']): cell for cell in result['cells']}
|
||||
for line in positioned:
|
||||
day = min(range(1, 6), key=lambda d: abs(line['x'] - columns[d]))
|
||||
if abs(line['x'] - columns[day]) >= step / 2 or line['y'] <= header_y: continue
|
||||
row = next((i for i in range(4) if bounds[i] <= line['y'] < bounds[i+1]), None)
|
||||
if row is None: continue
|
||||
text = compact(line['text'])
|
||||
if not text: continue
|
||||
cell = cells[(day, SLOTS[row]['id'])]
|
||||
empty = text in ('无课', '空闲', '无课程')
|
||||
if empty:
|
||||
if cell['status'] == 'unknown' and line['score'] >= .9:
|
||||
cell.update(status='free', confidence=line['score'])
|
||||
else:
|
||||
cell['status'] = 'busy'
|
||||
cell['courses'] = (cell['courses'] + '\n' + line['text']).strip()[:500]
|
||||
cell['confidence'] = min(cell['confidence'] or 1, line['score'])
|
||||
return result
|
||||
|
||||
|
||||
def recognize(raw):
|
||||
return structure_from_lines(read_image(raw))
|
||||
@@ -0,0 +1,196 @@
|
||||
"""单双周课表收取、本人校对、受限查阅及排班数据导出。"""
|
||||
import asyncio
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import Depends, HTTPException, Query, Request
|
||||
from fastapi.responses import FileResponse, Response
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import select, text
|
||||
from sqlalchemy.dialects.sqlite import insert
|
||||
|
||||
from .models import timetables, users
|
||||
from . import timetable_ocr as ocr
|
||||
|
||||
Week = Literal['odd', 'even']
|
||||
SLOT_IDS = [slot['id'] for slot in ocr.SLOTS]
|
||||
_recognition_slots = asyncio.Semaphore(1)
|
||||
|
||||
|
||||
class Cell(BaseModel):
|
||||
day: int = Field(ge=1, le=5)
|
||||
slot: Literal['1-2', '3-4', '5-6', '7-8']
|
||||
status: Literal['unknown', 'busy', 'free']
|
||||
courses: str = Field(default='', max_length=500)
|
||||
|
||||
|
||||
class Correction(BaseModel):
|
||||
revision: str = Field(min_length=32, max_length=80)
|
||||
cells: list[Cell] = Field(min_length=20, max_length=20)
|
||||
confirm: bool = False
|
||||
|
||||
|
||||
def now_ms(): return int(time.time() * 1000)
|
||||
|
||||
|
||||
def public_file(row):
|
||||
structure = json.loads(row['structure'])
|
||||
for cell in structure['cells']:
|
||||
cell['eligible'] = bool(row['confirmed_at']) and cell['status'] == 'free'
|
||||
return {'week_type': row['week_type'], 'revision': row['file_key'] + ':' + str(row['updated_at']), 'filename': row['filename'],
|
||||
'image_url': f"/api/timetables/{row['user_id']}/{row['week_type']}/file",
|
||||
'structure': structure, 'ocr_status': row['ocr_status'],
|
||||
'created_at': row['created_at'], 'updated_at': row['updated_at'], 'confirmed_at': row['confirmed_at']}
|
||||
|
||||
|
||||
def install(app, get_db, current_user, file_root, collector_emails):
|
||||
def can_collect(viewer):
|
||||
return viewer['email'].strip().lower() in collector_emails()
|
||||
|
||||
async def readable(db, viewer, user_id, week):
|
||||
if user_id != viewer['id'] and not can_collect(viewer):
|
||||
raise HTTPException(403, '仅本人及课表收取负责人可查看课表')
|
||||
row = (await db.execute(select(timetables).where(timetables.c.user_id == user_id, timetables.c.week_type == week))).mappings().first()
|
||||
if not row: raise HTTPException(404, '课表尚未上传')
|
||||
return row
|
||||
|
||||
@app.get('/api/timetables')
|
||||
async def collection(q: str = Query('', max_length=100), status: Literal['all', 'complete', 'incomplete', 'missing'] = 'all',
|
||||
db=Depends(get_db), viewer=Depends(current_user)):
|
||||
people = (await db.execute(select(users.c.id, users.c.display_name, users.c.department).order_by(users.c.display_name, users.c.id))).mappings().all()
|
||||
rows = (await db.execute(select(timetables))).mappings().all()
|
||||
grouped = {}
|
||||
for row in rows: grouped.setdefault(row['user_id'], {})[row['week_type']] = row
|
||||
complete = sum(len(grouped.get(person['id'], {})) == 2 for person in people)
|
||||
missing = sum(not grouped.get(person['id']) for person in people)
|
||||
members = []
|
||||
collector = can_collect(viewer)
|
||||
for person in people:
|
||||
weeks = grouped.get(person['id'], {})
|
||||
if q.strip().lower() not in (person['display_name'] + person['department']).lower(): continue
|
||||
if status == 'complete' and len(weeks) != 2: continue
|
||||
if status == 'incomplete' and len(weeks) == 2: continue
|
||||
if status == 'missing' and weeks: continue
|
||||
members.append({**person, 'can_read': collector or person['id'] == viewer['id'],
|
||||
'weeks': {week: {'submitted': week in weeks, 'confirmed': bool(weeks.get(week, {}).get('confirmed_at')),
|
||||
'updated_at': weeks[week]['updated_at'] if week in weeks else None} for week in ('odd', 'even')}})
|
||||
return {'mine': {week: public_file(grouped[viewer['id']][week]) if week in grouped.get(viewer['id'], {}) else None for week in ('odd', 'even')},
|
||||
'members': members, 'summary': {'total': len(people), 'complete': complete, 'partial': len(people)-complete-missing, 'missing': missing},
|
||||
'can_collect': collector, 'collector_configured': bool(collector_emails()), 'slots': ocr.SLOTS, 'days': ocr.DAYS}
|
||||
|
||||
@app.put('/api/timetables/me/{week}')
|
||||
async def upload(week: Week, request: Request, filename: str = Query(..., min_length=1, max_length=180),
|
||||
db=Depends(get_db), viewer=Depends(current_user)):
|
||||
filename = Path(filename.replace('\\', '/')).name
|
||||
if any(ord(char) < 32 or ord(char) == 127 for char in filename): raise HTTPException(422, '文件名无效')
|
||||
if Path(filename).suffix.lower() not in ('.jpg', '.jpeg', '.png', '.webp'):
|
||||
raise HTTPException(422, '请上传JPG、PNG或WebP课表图片')
|
||||
raw = bytearray()
|
||||
async for chunk in request.stream():
|
||||
raw.extend(chunk)
|
||||
if len(raw) > 10 * 1024 * 1024: raise HTTPException(413, '课表图片最大10MB')
|
||||
try: image = await asyncio.to_thread(ocr.normalize_image, bytes(raw))
|
||||
except Exception as exc: raise HTTPException(422, '课表图片无效,仅支持静态JPG、PNG、WebP,最大2400万像素') from exc
|
||||
# 识别失败仍保存图片,允许本人手动整理,不能返回虚假的识别结果。
|
||||
try:
|
||||
async with _recognition_slots:
|
||||
structure = await asyncio.to_thread(ocr.recognize, image)
|
||||
ocr_status = 'needs_review'
|
||||
except Exception:
|
||||
structure = ocr.blank_structure()
|
||||
structure['warnings'] = ['自动识别暂不可用,图片已保存,请手动整理并核对。']
|
||||
ocr_status = 'error'
|
||||
key = uuid.uuid4().hex + '.png'
|
||||
folder = file_root(); folder.mkdir(parents=True, exist_ok=True)
|
||||
path = folder / key
|
||||
old = None
|
||||
try:
|
||||
await asyncio.to_thread(path.write_bytes, image)
|
||||
await db.execute(text('BEGIN IMMEDIATE'))
|
||||
old = (await db.execute(select(timetables).where(timetables.c.user_id == viewer['id'], timetables.c.week_type == week))).mappings().first()
|
||||
stamp = now_ms()
|
||||
values = dict(user_id=viewer['id'], week_type=week, file_key=key, filename=filename,
|
||||
structure=json.dumps(structure, ensure_ascii=False), ocr_status=ocr_status,
|
||||
created_at=old['created_at'] if old else stamp, updated_at=stamp, confirmed_at=None)
|
||||
await db.execute(insert(timetables).values(**values).on_conflict_do_update(
|
||||
index_elements=['user_id', 'week_type'], set_={key: value for key, value in values.items() if key not in ('user_id', 'week_type', 'created_at')}))
|
||||
await db.commit()
|
||||
except Exception:
|
||||
await db.rollback(); path.unlink(missing_ok=True)
|
||||
raise
|
||||
if old:
|
||||
try: (folder / old['file_key']).unlink(missing_ok=True)
|
||||
except OSError: print('[timetables] 旧图片清理失败,当前课表已保存', flush=True)
|
||||
return {'timetable': public_file(values)}
|
||||
|
||||
@app.patch('/api/timetables/me/{week}')
|
||||
async def correct(week: Week, payload: Correction, db=Depends(get_db), viewer=Depends(current_user)):
|
||||
keys = {(cell.day, cell.slot) for cell in payload.cells}
|
||||
if keys != {(day, slot) for day in range(1, 6) for slot in SLOT_IDS}:
|
||||
raise HTTPException(422, '请完整填写20个时段,时段不能重复')
|
||||
if payload.confirm and any(cell.status == 'unknown' for cell in payload.cells):
|
||||
raise HTTPException(422, '仍有待确认时段,请核对后再确认')
|
||||
await db.execute(text('BEGIN IMMEDIATE'))
|
||||
row = await readable(db, viewer, viewer['id'], week)
|
||||
if public_file(row)['revision'] != payload.revision: raise HTTPException(409, '课表已修改或替换,请重新打开当前课表')
|
||||
structure = json.loads(row['structure'])
|
||||
structure['cells'] = [{**cell.model_dump(), 'source': 'manual', 'confidence': 1} for cell in payload.cells]
|
||||
values = {**row, 'structure': json.dumps(structure, ensure_ascii=False), 'updated_at': max(now_ms(), row['updated_at'] + 1),
|
||||
'confirmed_at': now_ms() if payload.confirm else None}
|
||||
from sqlalchemy import update
|
||||
await db.execute(update(timetables).where(timetables.c.user_id == viewer['id'], timetables.c.week_type == week).values(
|
||||
structure=values['structure'], updated_at=values['updated_at'], confirmed_at=values['confirmed_at']))
|
||||
await db.commit()
|
||||
return {'timetable': public_file(values)}
|
||||
|
||||
@app.get('/api/timetables/schema')
|
||||
async def schema(viewer=Depends(current_user)):
|
||||
return {'schema_version': 1, 'week_types': {'odd': '单周', 'even': '双周'}, 'days': ocr.DAYS, 'slots': ocr.SLOTS,
|
||||
'states': {'busy': '有课', 'free': '空闲', 'unknown': '待确认'},
|
||||
'export': '/api/timetables/export?format=json&confirmed_only=true',
|
||||
'privacy': '本人可导出自己的课表;收取负责人可导出全部;不包含邮箱和手机号',
|
||||
'eligibility': '仅已确认课表中的free时段可列为可值班;unknown不能当作空闲',
|
||||
'scope': '按当前值班时间整理周一至周五的四个时段;完整识别文字另存raw_text,夜间和周末未参与可值班判断'}
|
||||
|
||||
@app.get('/api/timetables/export')
|
||||
async def export(format: Literal['json', 'csv'] = 'json', confirmed_only: bool = True,
|
||||
db=Depends(get_db), viewer=Depends(current_user)):
|
||||
query = select(timetables, users.c.display_name, users.c.department).join(users).order_by(users.c.display_name, timetables.c.user_id, timetables.c.week_type)
|
||||
if not can_collect(viewer): query = query.where(timetables.c.user_id == viewer['id'])
|
||||
if confirmed_only: query = query.where(timetables.c.confirmed_at.is_not(None))
|
||||
found = (await db.execute(query)).mappings().all()
|
||||
records = [{**public_file(row), 'user_id': row['user_id'], 'display_name': row['display_name'], 'department': row['department']} for row in found]
|
||||
if format == 'json':
|
||||
body = json.dumps({'schema_version': 1, 'timezone': 'Asia/Shanghai', 'days': ocr.DAYS, 'slots': ocr.SLOTS,
|
||||
'confirmed_only': confirmed_only, 'records': records}, ensure_ascii=False, indent=2).encode('utf-8')
|
||||
mime = 'application/json'
|
||||
else:
|
||||
buffer = io.StringIO(newline='')
|
||||
fields = ['user_id','display_name','department','week_type','day','slot','start','end','status','courses','confirmed','eligible']
|
||||
writer = csv.DictWriter(buffer, fieldnames=fields); writer.writeheader()
|
||||
slots = {slot['id']: slot for slot in ocr.SLOTS}
|
||||
for record in records:
|
||||
for cell in record['structure']['cells']:
|
||||
row = {key: record[key] for key in ('user_id','display_name','department','week_type')}
|
||||
row.update({key: cell[key] for key in ('day','slot','status','courses')})
|
||||
row.update(start=slots[cell['slot']]['start'], end=slots[cell['slot']]['end'], confirmed=bool(record['confirmed_at']),
|
||||
eligible=bool(record['confirmed_at']) and cell['status'] == 'free')
|
||||
writer.writerow({key: "'"+value if isinstance(value, str) and value.lstrip().startswith(('=','+','-','@')) else value for key,value in row.items()})
|
||||
body = buffer.getvalue().encode('utf-8-sig'); mime = 'text/csv; charset=utf-8'
|
||||
return Response(body, media_type=mime, headers={'Content-Disposition': f'attachment; filename="timetables.{format}"'})
|
||||
|
||||
@app.get('/api/timetables/{user_id}/{week}')
|
||||
async def detail(user_id: str, week: Week, db=Depends(get_db), viewer=Depends(current_user)):
|
||||
return {'timetable': public_file(await readable(db, viewer, user_id, week))}
|
||||
|
||||
@app.get('/api/timetables/{user_id}/{week}/file')
|
||||
async def image(user_id: str, week: Week, download: bool = False, db=Depends(get_db), viewer=Depends(current_user)):
|
||||
row = await readable(db, viewer, user_id, week)
|
||||
path = file_root() / row['file_key']
|
||||
if not path.is_file(): raise HTTPException(404, '课表图片文件不存在')
|
||||
return FileResponse(path, media_type='image/png', filename=Path(row['filename']).stem+'.png' if download else None)
|
||||
@@ -0,0 +1,167 @@
|
||||
import asyncio
|
||||
import copy
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from PIL import Image
|
||||
from sqlalchemy import select, func
|
||||
from server import timetable_ocr as ocr
|
||||
from server.models import timetables
|
||||
from test_api import ApiTestCase, auth, register
|
||||
|
||||
|
||||
def image_bytes(color='blue'):
|
||||
stream = io.BytesIO(); Image.new('RGB', (30, 30), color).save(stream, 'PNG')
|
||||
return stream.getvalue()
|
||||
|
||||
|
||||
def recognized():
|
||||
data = ocr.blank_structure()
|
||||
data['cells'][0].update(status='busy', courses='高等数学', confidence=.95)
|
||||
data['raw_text'] = '高等数学'
|
||||
return data
|
||||
|
||||
|
||||
class TimetableParsingTests(unittest.TestCase):
|
||||
def test_coordinates_keep_blank_cells_unknown_and_map_busy_and_explicit_free(self):
|
||||
def line(x, y, text, score=.99):
|
||||
return {'box': [[x-30,y-10],[x+30,y-10],[x+30,y+10],[x-30,y+10]], 'text': text, 'score': score}
|
||||
lines = [line(150+100*i, 30, '星期'+'一二三四五六日'[i]) for i in range(7)]
|
||||
lines += [line(30, 120+100*i, f'{i*2+1}-{i*2+2}节') for i in range(4)]
|
||||
lines += [line(150,120,'高等数学'),line(550,420,'无课'),line(250,220,'空闲',.6)]
|
||||
result = ocr.structure_from_lines(lines)
|
||||
cells = {(cell['day'],cell['slot']):cell for cell in result['cells']}
|
||||
self.assertEqual(cells[(1,'1-2')]['status'],'busy')
|
||||
self.assertEqual(cells[(5,'7-8')]['status'],'free')
|
||||
self.assertEqual(cells[(2,'3-4')]['status'],'unknown')
|
||||
self.assertEqual(cells[(4,'1-2')]['status'],'unknown')
|
||||
self.assertEqual(len(result['cells']),20)
|
||||
self.assertIn('高等数学',result['raw_text'])
|
||||
|
||||
def test_missing_headers_never_invent_availability(self):
|
||||
self.assertEqual(ocr.weekday('星期天'), 7)
|
||||
self.assertEqual(ocr.periods('第一节'), [1])
|
||||
self.assertEqual(ocr.periods('3—4节'), [3, 4])
|
||||
result = ocr.structure_from_lines([])
|
||||
self.assertTrue(all(cell['status']=='unknown' for cell in result['cells']))
|
||||
self.assertGreater(len(result['warnings']),1)
|
||||
|
||||
|
||||
class TimetableTests(ApiTestCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.files = tempfile.TemporaryDirectory()
|
||||
self.root = Path(self.files.name)
|
||||
self.db_path_patch = patch.object(self.m, '_db_path', self.root/'test.db'); self.db_path_patch.start()
|
||||
self.ocr_patch = patch('server.timetable_ocr.recognize', side_effect=lambda raw: recognized()); self.ocr_patch.start()
|
||||
self.collector_patch = patch.dict(os.environ, WORKLOG_TIMETABLE_COLLECTORS=''); self.collector_patch.start()
|
||||
|
||||
def tearDown(self):
|
||||
self.collector_patch.stop(); self.ocr_patch.stop(); self.db_path_patch.stop(); self.files.cleanup()
|
||||
super().tearDown()
|
||||
|
||||
async def upload(self, user, week='odd', color='blue'):
|
||||
result = await self.client.put('/api/timetables/me/'+week+'?filename=课表.png', headers=auth(user['token']), content=image_bytes(color))
|
||||
self.assertEqual(result.status_code,200,result.text)
|
||||
return result.json()['timetable']
|
||||
|
||||
async def confirm(self, user, timetable, confirm=True):
|
||||
cells = copy.deepcopy(timetable['structure']['cells'])
|
||||
for cell in cells:
|
||||
if cell['status']=='unknown': cell['status']='free'
|
||||
return await self.client.patch('/api/timetables/me/'+timetable['week_type'],headers=auth(user['token']),json={'revision':timetable['revision'],'cells':cells,'confirm':confirm})
|
||||
|
||||
async def test_authenticated_image_only_validation(self):
|
||||
for path in ['/api/timetables','/api/timetables/schema','/api/timetables/export']:
|
||||
self.assertEqual((await self.client.get(path)).status_code,401)
|
||||
self.assertEqual((await self.client.put('/api/timetables/me/odd?filename=a.png',content=image_bytes())).status_code,401)
|
||||
user = await register(self.client,'timetableformats'); headers = auth(user['token'])
|
||||
for name,content,expected in [('a.png',b'<script>bad</script>',422),('a.zip',image_bytes(),422),('a.png',b'x'*(10*1024*1024+1),413)]:
|
||||
result = await self.client.put('/api/timetables/me/odd?filename='+name,headers=headers,content=content)
|
||||
self.assertEqual(result.status_code,expected,result.text)
|
||||
self.assertEqual((await self.client.put('/api/timetables/me/wrong?filename=a.png',headers=headers,content=image_bytes())).status_code,422)
|
||||
self.assertFalse((self.root/'timetables').exists())
|
||||
|
||||
async def test_one_file_per_week_replacement_and_revision_protection(self):
|
||||
user = await register(self.client,'timetableowner'); first = await self.upload(user)
|
||||
confirmed = await self.confirm(user,first)
|
||||
self.assertEqual(confirmed.status_code,200,confirmed.text)
|
||||
saved = confirmed.json()['timetable']; self.assertIsNotNone(saved['confirmed_at'])
|
||||
self.assertEqual((await self.confirm(user,first)).status_code,409)
|
||||
even = await self.upload(user,'even')
|
||||
updated = await self.upload(user,'odd','red')
|
||||
self.assertNotEqual(first['revision'],updated['revision']); self.assertIsNone(updated['confirmed_at'])
|
||||
self.assertEqual(first['created_at'],updated['created_at'])
|
||||
self.assertEqual((await self.confirm(user,saved)).status_code,409)
|
||||
collection = (await self.client.get('/api/timetables',headers=auth(user['token']))).json()
|
||||
self.assertEqual(collection['mine']['even']['revision'],even['revision'])
|
||||
self.assertEqual(collection['summary']['complete'],1)
|
||||
async with self.sessions() as db:
|
||||
self.assertEqual((await db.execute(select(func.count()).select_from(timetables))).scalar(),2)
|
||||
self.assertEqual(len(list((self.root/'timetables').glob('*.png'))),2)
|
||||
file = await self.client.get(updated['image_url'],headers=auth(user['token']))
|
||||
self.assertEqual(file.status_code,200); self.assertEqual(file.headers['content-type'],'image/png')
|
||||
|
||||
async def test_roster_only_reveals_status_and_collectors_can_read_without_editing(self):
|
||||
owner = await register(self.client,'privatetimetable'); other = await register(self.client,'timetablereader')
|
||||
item = await self.upload(owner)
|
||||
listing = await self.client.get('/api/timetables',headers=auth(other['token']))
|
||||
self.assertNotIn('高等数学',listing.text); self.assertNotIn('课表.png',listing.text)
|
||||
self.assertNotIn(owner['user']['email'],listing.text)
|
||||
row = next(row for row in listing.json()['members'] if row['id']==owner['user']['id'])
|
||||
self.assertTrue(row['weeks']['odd']['submitted']); self.assertFalse(row['can_read'])
|
||||
path = '/api/timetables/'+owner['user']['id']+'/odd'
|
||||
for suffix in ('','/file'):
|
||||
self.assertEqual((await self.client.get(path+suffix,headers=auth(other['token']))).status_code,403)
|
||||
with patch.dict(os.environ,WORKLOG_TIMETABLE_COLLECTORS=other['user']['email'].upper()):
|
||||
self.assertEqual((await self.client.get(path,headers=auth(other['token']))).status_code,200)
|
||||
self.assertEqual((await self.client.get(path+'/file',headers=auth(other['token']))).status_code,200)
|
||||
self.assertIn((await self.client.patch(path,headers=auth(other['token']),json={})).status_code,(403,405))
|
||||
self.assertTrue((await self.client.get('/api/timetables',headers=auth(other['token']))).json()['can_collect'])
|
||||
|
||||
async def test_confirm_requires_complete_grid_and_exports_only_verified_free_slots(self):
|
||||
owner = await register(self.client,'timetableexport'); other = await register(self.client,'timetableexportother')
|
||||
item = await self.upload(owner); await self.upload(owner,'even'); await self.upload(other)
|
||||
path = '/api/timetables/me/odd'; headers = auth(owner['token'])
|
||||
result = await self.client.patch(path,headers=headers,json={'revision':item['revision'],'cells':item['structure']['cells'],'confirm':True})
|
||||
self.assertEqual(result.status_code,422)
|
||||
duplicate = [item['structure']['cells'][0]]*20
|
||||
self.assertEqual((await self.client.patch(path,headers=headers,json={'revision':item['revision'],'cells':duplicate})).status_code,422)
|
||||
self.assertEqual((await self.client.get('/api/timetables/export',headers=headers)).json()['records'],[])
|
||||
result = await self.confirm(owner,item); self.assertEqual(result.status_code,200,result.text)
|
||||
data = await self.client.get('/api/timetables/export',headers=headers)
|
||||
self.assertEqual(len(data.json()['records']),1); self.assertNotIn(owner['user']['email'],data.text)
|
||||
csv_response = await self.client.get('/api/timetables/export?format=csv',headers=headers)
|
||||
rows = list(csv.DictReader(io.StringIO(csv_response.content.decode('utf-8-sig'))))
|
||||
self.assertEqual(len(rows),20); self.assertEqual(sum(row['eligible']=='True' for row in rows),19)
|
||||
all_own = (await self.client.get('/api/timetables/export?confirmed_only=false',headers=headers)).json()['records']
|
||||
self.assertEqual(len(all_own),2)
|
||||
with patch.dict(os.environ,WORKLOG_TIMETABLE_COLLECTORS=owner['user']['email']):
|
||||
self.assertEqual(len((await self.client.get('/api/timetables/export?confirmed_only=false',headers=headers)).json()['records']),3)
|
||||
|
||||
async def test_recognition_failure_preserves_image_for_manual_correction(self):
|
||||
user = await register(self.client,'timetablefallback')
|
||||
with patch('server.timetable_ocr.recognize',side_effect=RuntimeError('private error')):
|
||||
item = await self.upload(user)
|
||||
self.assertEqual(item['ocr_status'],'error'); self.assertNotIn('private error',json.dumps(item))
|
||||
self.assertEqual((await self.client.get(item['image_url'],headers=auth(user['token']))).status_code,200)
|
||||
self.assertEqual((await self.confirm(user,item)).status_code,200)
|
||||
|
||||
async def test_concurrent_uploads_keep_only_latest_one_file_for_each_week(self):
|
||||
engine = self.m.create_async_engine('sqlite+aiosqlite:///'+(self.root/'concurrency.db').as_posix())
|
||||
try:
|
||||
async with engine.begin() as connection: await connection.run_sync(self.m.metadata.create_all)
|
||||
sessions = self.m.async_sessionmaker(engine,expire_on_commit=False)
|
||||
with patch.object(self.m,'SessionLocal',sessions):
|
||||
user = await register(self.client,'timetableconcurrent')
|
||||
await asyncio.gather(self.upload(user,color='red'),self.upload(user,color='blue'))
|
||||
async with sessions() as db:
|
||||
self.assertEqual((await db.execute(select(func.count()).select_from(timetables))).scalar(),1)
|
||||
self.assertEqual(len(list((self.root/'timetables').glob('*.png'))),1)
|
||||
finally: await engine.dispose()
|
||||
Reference in New Issue
Block a user