优化彩色课表占用识别,仅记录有课无课并简化校对

This commit is contained in:
2026-11-12 16:21:32 +08:00
parent 0dbb5063ec
commit 2c6e12f831
6 changed files with 387 additions and 70 deletions
+6 -4
View File
@@ -2,13 +2,15 @@
登录后进入“课表收取”,或打开 `/#timetables`。活动墙也有快捷入口。 登录后进入“课表收取”,或打开 `/#timetables`。活动墙也有快捷入口。
单周、双周分别上传一张 JPG、PNG 或 WebP 图片,单张原文件最大 10MB、2400 万像素。每个账号每种周次只保留一份当前课表,修改会替换该周的图片及识别结果,另一周不变;旧图在新记录保存成功后清理。上传显示传输进度,随后显示识别处理状态。 单周、双周分别上传一张 JPG、PNG 或 WebP 图片,单张原文件最大 10MB、2400 万像素。每个账号每种周次只保留一份当前课表,修改会替换该周的图片及识别结果,另一周不变;旧图在新记录保存成功后清理。上传显示传输进度,随后显示识别处理状态。只记录有课/无课,不再整理课程名、教师和教室。
图片会转成不含 EXIF 的 PNG 保存。数据库中的 `timetables` 表以 `(user_id, week_type)` 为主键,并发提交也不会产生重复课表;首次提交时间保留,修改会更新修改时间并清除此前的核对确认。更新失败会保留上一份记录。修改表格时校验版本,其他设备已经修改或替换后需要重新打开,避免覆盖新内容。 图片会转成不含 EXIF 的 PNG 保存。数据库中的 `timetables` 表以 `(user_id, week_type)` 为主键,并发提交也不会产生重复课表;首次提交时间保留,修改会更新修改时间并清除此前的核对确认。更新失败会保留上一份记录。修改表格时校验版本,其他设备已经修改或替换后需要重新打开,避免覆盖新内容。
## 自动整理与核对 ## 自动整理与核对
安装 `requirements.txt`(新增 RapidOCR 及 ONNX Runtime)即可在服务器本地识别图片,不需要外部识别服务账号,也不发送课表到外部平台。采用 RapidOCR 3.10 系列默认附带的中文模型,首次识别加载模型会比后续慢;普通 CPU 即可运行,每次识别最多使用两个推理线程,同一服务进程按顺序执行识别任务。 安装 `requirements.txt`(RapidOCR、ONNX Runtime)即可在服务器本地处理图片,不需要外部识别服务账号,也不发送课表到外部平台。对常见彩色周课表,先提取课程块,再把星期表头和左侧节次拼为小图识别,只读取定位文字;跨多节、贴边或相同颜色相邻课程按日期列及覆盖时段分别计入。JPG色差通过重叠色域和形态学处理缓解。支持“一、二、三”等单字星期表头,以及单节、双节和时间标签。
每次推理最多两个CPU线程,检测图长边限制为1600像素,避免长截图按短边放大造成额外计算。服务进程保留最近16张相同图片的解析缓存,仅保存结构结果,不保留额外图片副本;重试、重复提交单双周同一张图可复用结果。结果独立复制,校对不会修改缓存。首次加载模型仍比后续慢。
参考:[RapidOCR 使用说明](https://rapidai.github.io/RapidOCRDocs/main/en/install_usage/rapidocr/usage/)。 参考:[RapidOCR 使用说明](https://rapidai.github.io/RapidOCRDocs/main/en/install_usage/rapidocr/usage/)。
@@ -21,9 +23,9 @@
| `5-6` | 五六节 | 14:00–15:45 | | `5-6` | 五六节 | 14:00–15:45 |
| `7-8` | 七八节 | 16:00–17:45 | | `7-8` | 七八节 | 16:00–17:45 |
程序根据图片中的星期列和节次或时间行定位课程文字,整理为“有课 / 空闲 / 待确认”。支持常见星期中文或英文表头,节次数字或“一二节”等标签。无法定位完整星期或节次时保留全部识别文字,并提示手动整理;夜间和周末的识别文字仍保留在 `raw_text`,不参与当前值班时段判断。 程序根据星期列、节次以及课程块覆盖范围整理周一至周五20个时段。完整定位的彩色课表可根据留白建议“无课”,仅保存 `busy` / `free`;课程名、教师、教室和识别原文留空。表格未完整展示、缺少可靠定位或不是彩色课表时,回退文字位置判断,无法确定的时段保持 `unknown`,不会把识别失败当作无课。节次与星期仅有少量漏字时可参考相邻标签定位;边界或行位置不可靠则交由本人核对。晚间和周末课程不参与当前四个值班时段判断。
图片识别不能保证所有排版、合并课程块和跨节课程都能准确还原,必须对照原图核对。没有识别到文字的位置保持“待确认”,只有明确识别到“无课 / 空闲”等内容时才建议为空闲。本人可编辑每个时段的状态和课程备注,或在核对后将其余待确认设为空闲。保存草稿不会确认;只有20个时段均已明确,才能点击“核对无误并确认”。识别组件异常时仍保存图片,并提供手动整理,不返回虚假的识别成功结果。 本人在校对页面只需选择“有课 / 无课”,定位失败时保留“待确认”。界面显示有课、无课及待确认时段数,不再要求填写课程备注。核对后可将其余待确认设为无课。保存草稿不等于确认;只有20个时段均已明确,才能点击“核对无误并确认”。识别组件异常时仍保存图片并提供手动整理。自动结果始终需要核对,只有已确认的无课时段才可供排班使用。
这次仅收取和整理数据,不会自动修改已有值班表或发送额外邮件。 这次仅收取和整理数据,不会自动修改已有值班表或发送额外邮件。
+2 -2
View File
@@ -179,7 +179,7 @@
<main id="timetables-view" class="view hidden"> <main id="timetables-view" class="view hidden">
<div class="container"> <div class="container">
<div class="page-head"><div><h2>课表收取</h2><p class="muted">单周、双周分别提交,每类只保留一份,后续可修改替换。</p></div></div> <div class="page-head"><div><h2>课表收取</h2><p class="muted">单周、双周分别提交,每类只保留一份,后续可修改替换。</p></div></div>
<p class="muted">上传课表图片后自动整理为值班时段表,请对照原图核对。课表仅本人及收取负责人可查看,其他成员只看到提交状态。</p> <p class="muted">上传课表图片后自动整理有课/无课时段,请对照原图核对。课表仅本人及收取负责人可查看,其他成员只看到提交状态。</p>
<p class="muted" id="timetable-collector-note"></p> <p class="muted" id="timetable-collector-note"></p>
<div id="timetable-mine" class="timetable-mine"></div> <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="page-head center-subhead"><div><h3>收取进度</h3><p class="muted" id="timetable-summary" role="status"></p></div></div>
@@ -322,7 +322,7 @@
<div id="toast" class="toast hidden" role="status" aria-live="polite"></div> <div id="toast" class="toast hidden" role="status" aria-live="polite"></div>
<script src="/js/app.js?v=31"></script> <script src="/js/app.js?v=32"></script>
</div> </div>
</body> </body>
</html> </html>
+8 -10
View File
@@ -1252,16 +1252,17 @@
const editable = userId === state.me.id; const editable = userId === state.me.id;
const cells = item.structure.cells; const cells = item.structure.cells;
const slots = timetableData.slots, days = timetableData.days; const slots = timetableData.slots, days = timetableData.days;
const statusLabels = { unknown: '待确认', busy: '有课', free: '空闲' }; const statusLabels = { unknown: '待确认', busy: '有课', free: '无课' };
modal(`<h3>${weekLabel(item.week_type)}课表 · ${editable ? '核对与修改' : '查看'}</h3><p class="modal-sub muted">按现有四个值班时段整理周一至周五。请对照原图检查,核对后再用于排班。</p> const counts = {busy:0, free:0, unknown:0}; cells.forEach(cell => counts[cell.status]++);
const recognitionSummary = `${counts.busy}个有课时段 · ${counts.free}个无课时段${counts.unknown ? ' · ' + counts.unknown + '个待确认' : ''}`;
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-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> <p class="muted">${recognitionSummary}</p><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) => { <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]; 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>`; 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>` : `<strong>${statusLabels[cell.status]}</strong>`}</td>`;
}).join('')}</tr>`).join('')}</tbody></table></div> }).join('')}</tr>`).join('')}</tbody></table></div>
${editable ? '<button class="btn sm" type="button" id="timetable-fill-free">将其余待确认设为空闲</button>' : ''} ${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-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>`); <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'); $('#modal-root .modal').classList.add('timetable-editor');
@@ -1285,9 +1286,6 @@
select.closest('td').dataset.status = select.value; select.closest('td').dataset.status = select.value;
form.querySelector('#timetable-confirmation-state').textContent = '有未保存修改,请重新保存并确认。'; 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', () => { $('#timetable-fill-free').addEventListener('click', () => {
form.querySelectorAll('[data-cell]').forEach(select => { if (select.value === 'unknown') { select.value = 'free'; select.dispatchEvent(new Event('change')); } }); form.querySelectorAll('[data-cell]').forEach(select => { if (select.value === 'unknown') { select.value = 'free'; select.dispatchEvent(new Event('change')); } });
}); });
@@ -1295,7 +1293,7 @@
form.addEventListener('submit', async event => { form.addEventListener('submit', async event => {
event.preventDefault(); if (saving) return; event.preventDefault(); if (saving) return;
const confirm = event.submitter?.dataset.confirm === 'true'; 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 edited = cells.map((cell,index) => ({ day: cell.day, slot: cell.slot, status: form.querySelector(`[data-cell="${index}"]`).value, courses: '' }));
const errorBox = form.querySelector('.form-error'); errorBox.textContent = ''; const errorBox = form.querySelector('.form-error'); errorBox.textContent = '';
if (confirm && edited.some(cell => cell.status === 'unknown')) { errorBox.textContent = '仍有待确认时段,请核对后再确认'; return; } if (confirm && edited.some(cell => cell.status === 'unknown')) { errorBox.textContent = '仍有待确认时段,请核对后再确认'; return; }
saving = true; form.querySelectorAll('[type=submit]').forEach(button => button.disabled = true); saving = true; form.querySelectorAll('[type=submit]').forEach(button => button.disabled = true);
+282 -53
View File
@@ -1,5 +1,9 @@
"""本地图片识别及值班时段整理。留白保持待确认,不能直接当作空闲。""" """本地图片识别及值班时段整理。留白保持待确认,不能直接当作空闲。"""
import io import io
import copy
import hashlib
import time
from collections import OrderedDict
import re import re
import threading import threading
import unicodedata import unicodedata
@@ -16,6 +20,8 @@ SLOTS = [
DAYS = ['周一', '周二', '周三', '周四', '周五'] DAYS = ['周一', '周二', '周三', '周四', '周五']
_engine = None _engine = None
_lock = threading.Lock() _lock = threading.Lock()
_cache = OrderedDict()
_cache_lock = threading.Lock()
def blank_structure(): def blank_structure():
@@ -33,7 +39,7 @@ def normalize_image(raw):
if getattr(image, 'n_frames', 1) != 1: if getattr(image, 'n_frames', 1) != 1:
raise ValueError('请上传静态课表图片') raise ValueError('请上传静态课表图片')
image = ImageOps.exif_transpose(image).convert('RGB') image = ImageOps.exif_transpose(image).convert('RGB')
output = io.BytesIO(); image.save(output, 'PNG') output = io.BytesIO(); image.save(output, 'PNG', compress_level=1)
return output.getvalue() return output.getvalue()
@@ -43,7 +49,8 @@ def read_image(raw):
if _engine is None: if _engine is None:
from rapidocr import RapidOCR from rapidocr import RapidOCR
_engine = RapidOCR(params={ _engine = RapidOCR(params={
'Global.log_level': 'error', 'Global.max_side_len': 2400, 'Global.log_level': 'error', 'Global.max_side_len': 2000,
'Det.limit_side_len': 1600, 'Det.limit_type': 'max',
'EngineConfig.onnxruntime.intra_op_num_threads': 2, 'EngineConfig.onnxruntime.intra_op_num_threads': 2,
'EngineConfig.onnxruntime.inter_op_num_threads': 1, 'EngineConfig.onnxruntime.inter_op_num_threads': 1,
}) })
@@ -60,6 +67,10 @@ def compact(value):
def weekday(text): def weekday(text):
value = compact(text) value = compact(text)
if value in '一二三四五六日天' and len(value)==1:
return 7 if value in '日天' else '一二三四五六'.index(value)+1
if value in ('-', '—', '一'):
return 1
match = re.match(r'^(?:星期|礼拜|周)([一二三四五六日天1-7])', value) match = re.match(r'^(?:星期|礼拜|周)([一二三四五六日天1-7])', value)
if match: if match:
token = match[1] token = match[1]
@@ -69,81 +80,299 @@ def weekday(text):
def periods(text): def periods(text):
value = compact(text).replace('第', '').replace('节次', '').replace('节', '') value = compact(text).replace('节次', '节').replace('第', '')
value = value.replace('—', '-').replace('–', '-') value = re.sub(r'[—–-~~至]', '-', value)
chinese = {'一二': [1, 2], '三四': [3, 4], '五六': [5, 6], '七八': [7, 8]} # 时间、周次和课程名中的数字不能当作节次。
if len(value) == 1 and value in '一二三四五六七八': return ['一二三四五六七八'.index(value) + 1] value = re.split(r'节|[((\[]|\n', value, maxsplit=1)[0]
if value.replace('、', '') in chinese: return chinese[value.replace('、', '')] chinese = {word: i for i, word in enumerate(('一','二','三','四','五','六','七','八','九','十','十一','十二'), 1)}
if value in chinese: return chinese[value] if value in chinese: return [chinese[value]]
match = re.fullmatch(r'(\d{1,2})(?:[-~至、](\d{1,2}))?', value) for pair in ('一二', '三四', '五六', '七八', '九十'):
if value.replace('、', '') == pair:
return [chinese[pair[0]], chinese[pair[1]]]
for word, number in sorted(chinese.items(), key=lambda item: -len(item[0])):
value = value.replace(word, str(number))
match = re.fullmatch(r'(\d{1,2})(?:[-、,](\d{1,2}))?', value)
if not match: return [] if not match: return []
start = int(match[1]); end = int(match[2] or start) start = int(match[1]); end = int(match[2] or start)
return list(range(start, end + 1)) if 1 <= start <= end <= 12 else [] return list(range(start, end + 1)) if 1 <= start <= end <= 12 else []
def structure_from_lines(lines): def _positioned(lines):
result = blank_structure()
result['raw_text'] = '\n'.join(line['text'] for line in lines)[:100000]
result['warnings'] = ['识别结果需核对。未识别到文字的时段保持待确认,不自动判为空闲。']
positioned = [] positioned = []
for line in lines: for line in lines:
xs = [point[0] for point in line['box']]; ys = [point[1] for point in line['box']] 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, positioned.append({**line, 'x': (min(xs) + max(xs)) / 2, 'y': (min(ys) + max(ys)) / 2,
'height': max(ys) - min(ys)}) 'top': min(ys), 'bottom': max(ys), 'height': max(ys) - min(ys)})
return positioned
def _columns(positioned):
headers = [line for line in positioned if weekday(line['text'])] headers = [line for line in positioned if weekday(line['text'])]
groups = [] candidates = []
for header in headers: for header in headers:
group = [line for line in headers if abs(line['y'] - header['y']) < max(15, header['height'] * 1.5)] group = [line for line in headers if abs(line['y'] - header['y']) < max(15, header['height'] * 1.5)]
groups.append(group) columns = {}
selected = max(groups, key=lambda group: len({weekday(line['text']) for line in group}), default=[]) for line in group:
columns = {weekday(line['text']): line['x'] for line in selected} columns.setdefault(weekday(line['text']), []).append(line['x'])
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)): unique = {day:xs[0] for day,xs in columns.items() if len(xs)==1}
result['warnings'].append('未能完整定位周一至周五列,请对照原图手动整理。') days = sorted(unique)
return result if len(days)>=3:
step = median(columns[d+1] - columns[d] for d in range(1, 5)) guessed_step=median((unique[b]-unique[a])/(b-a) for a,b in zip(days,days[1:]))
left = columns[1] - step / 2 origin=median(unique[d]-(d-1)*guessed_step for d in days)
header_y = median(line['y'] for line in selected) columns={day:min(xs,key=lambda x:abs(x-(origin+(day-1)*guessed_step))) for day,xs in columns.items()}
else:
columns={day:median(xs) for day,xs in columns.items()}
days = sorted(columns)
if len(days) < 3: continue
step = median((columns[b] - columns[a]) / (b-a) for a,b in zip(days, days[1:]))
if step <= 0: continue
origin = median(columns[day] - (day-1)*step for day in days)
if any(abs(columns[day] - (origin+(day-1)*step)) > step*.2 for day in days): continue
candidates.append((len(days), -median(line['y'] for line in group), origin, step, columns, group))
if not candidates: return None
_, _, origin, step, columns, group = max(candidates, key=lambda item: item[:2])
inferred = [day for day in range(1,6) if day not in columns]
# 内部漏字可内插;至少5个星期锚点时仅外推相邻的一列,并在图像路径核对边界。
usable = {day: columns.get(day, origin+(day-1)*step) for day in range(1,6)
if min(columns)<=day<=max(columns) or (len(columns)>=5 and min(columns)-1<=day<=max(columns)+1)}
return usable, step, median(line['y'] for line in group), inferred
def _rows(positioned, left, header_y):
anchors = {slot['id']: [] for slot in SLOTS} anchors = {slot['id']: [] for slot in SLOTS}
section_y = {}
for line in positioned: for line in positioned:
if line['x'] >= left or line['y'] <= header_y: continue if line['x'] >= left or line['y'] <= header_y: continue
nums = periods(line['text']) nums = periods(line['text'])
if nums and len(nums) <= 2: if nums:
for number in nums:
section_y.setdefault(number, []).append(line['y'])
for index, slot in enumerate(SLOTS): for index, slot in enumerate(SLOTS):
if any(number in (index * 2 + 1, index * 2 + 2) for number in nums): if any(number in (index*2+1,index*2+2) for number in nums):
anchors[slot['id']].append(line['y']) anchors[slot['id']].append(line['y'])
value = compact(line['text']) value = compact(line['text']).replace(':', ':')
for slot in SLOTS: for slot in SLOTS:
if re.match(r'^0?' + re.escape(slot['start'].lstrip('0')) + r'(?:$|[-~])', value): if re.match(r'^0?' + re.escape(slot['start'].lstrip('0')) + r'(?:$|[-~~—])', value):
anchors[slot['id']].append(line['y']) # 有节次文字时优先节次,避免小号时间标签拉偏行中心。
if not all(anchors.values()): if not anchors[slot['id']]: anchors[slot['id']].append(line['y'])
result['warnings'].append('未能完整定位一二、三四、五六、七八节,请手动核对时段。') # OCR可能把晚间的9读成6;重复节次用前后节次定位,不能把行中心拉到晚间。
for number,ys in section_y.items():
if len(ys)>1 and number-1 in section_y and number+1 in section_y:
expected=(median(section_y[number-1])+median(section_y[number+1]))/2
section_y[number]=[min(ys,key=lambda y:abs(y-expected))]
centers={}
for i,slot in enumerate(SLOTS):
ys=[median(section_y[n]) for n in (i*2+1,i*2+2) if n in section_y]
if ys: centers[i]=median(ys)
elif anchors[slot['id']]: centers[i]=median(anchors[slot['id']])
known = sorted(centers)
if len(known) < 2 or any(centers[a] >= centers[b] for a,b in zip(known,known[1:])):
return {}, []
step = median((centers[b]-centers[a])/(b-a) for a,b in zip(known,known[1:]))
if any(not step*.5 <= (centers[b]-centers[a])/(b-a) <= step*1.8 for a,b in zip(known,known[1:])):
return {}, []
inferred = []
# 仅内插一个漏识别的行,保留无法确定的首尾行。
if len(known) >= 3:
for i in range(min(known),max(known)+1):
if i not in centers:
lo=max(k for k in known if k<i);hi=min(k for k in known if k>i)
centers[i]=centers[lo]+(centers[hi]-centers[lo])*(i-lo)/(hi-lo);inferred.append(i)
rows = {}
for i,center in centers.items():
top = (centers[i-1]+center)/2 if i-1 in centers else center-step/2
bottom = (center+centers[i+1])/2 if i+1 in centers else center+step/2
# 晚间节次定位最后一行下沿,防止夜课被算入七八节。
if i == 3 and 9 in section_y:
bottom = min(bottom,(max(section_y.get(8,[center]))+min(section_y[9]))/2)
rows[i]=(top,bottom)
return rows, inferred
def course_blocks(raw):
"""常见彩色课程卡片的边界,用于还原跨节课程;无明确边界时使用文字位置。"""
import cv2
import numpy as np
with Image.open(io.BytesIO(raw)) as image:
original = image.size
image = image.convert('RGB'); image.thumbnail((1200,1200))
rgb = np.array(image)
hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV)
sx,sy=original[0]/rgb.shape[1],original[1]/rgb.shape[0]
blocks=[]
# 按色相分开连通区域,紧贴的红、绿、蓝课程卡片不能粘成一个大块。
for hue in range(0,180,15):
distance=np.abs(hsv[:,:,0].astype('int16')-hue)
distance=np.minimum(distance,180-distance)
mask=((distance<=12)&(hsv[:,:,1]>=28)&(hsv[:,:,2]>=100)).astype('uint8')*255
mask=cv2.morphologyEx(mask,cv2.MORPH_OPEN,np.ones((3,3),np.uint8))
mask=cv2.morphologyEx(mask,cv2.MORPH_CLOSE,np.ones((3,3),np.uint8))
count,_,stats,_=cv2.connectedComponentsWithStats(mask,connectivity=4)
blocks.extend((float(x*sx),float(y*sy),float((x+w)*sx),float((y+h)*sy))
for x,y,w,h,area in stats[1:count] if w>=15 and h>=20 and area>=w*h*.6)
# 重叠色域避免JPEG边缘色差切碎卡片;只保留未被较大矩形覆盖的区域。
kept=[]
for box in sorted(blocks,key=lambda b:(b[2]-b[0])*(b[3]-b[1]),reverse=True):
x1,y1,x2,y2=box;area=(x2-x1)*(y2-y1)
if any(max(0,min(x2,b[2])-max(x1,b[0]))*max(0,min(y2,b[3])-max(y1,b[1]))>=area*.9 for b in kept):continue
kept.append(box)
return kept
def structure_from_lines(lines, blocks=()):
result = blank_structure()
result['raw_text'] = '\n'.join(line['text'] for line in lines)[:100000]
result['warnings'] = ['识别结果需核对。未识别到文字的时段保持待确认,不自动判为空闲。']
positioned = _positioned(lines)
layout = _columns(positioned)
if not layout:
result['warnings'].append('星期列定位不足,请保留完整表头并对照原图整理。')
return result return result
centers = [median(anchors[slot['id']]) for slot in SLOTS] columns, step, header_y, inferred_days = layout
if any(centers[i] >= centers[i+1] for i in range(3)): if inferred_days:
result['warnings'].append('节次位置不明确,请手动整理。') result['warnings'].append('部分星期文字未识别,已参考相邻列定位;请重点核对。')
return result left = min(columns.values()) - step/2
bounds = [centers[0] - (centers[1] - centers[0]) / 2, rows, inferred_rows = _rows(positioned,left,header_y)
*[(centers[i] + centers[i+1]) / 2 for i in range(3)], if len(rows)<4:
centers[-1] + (centers[-1] - centers[-2]) / 2] result['warnings'].append('部分节次未定位,已保留可定位时段,其余请手动核对。')
if inferred_rows:
result['warnings'].append('部分节次标签漏识别,已参考相邻行定位;请重点核对。')
if not rows: return result
cells = {(cell['day'], cell['slot']): cell for cell in result['cells']} cells = {(cell['day'], cell['slot']): cell for cell in result['cells']}
for line in positioned: for line in sorted(positioned,key=lambda line:(line['y'],line['x'])):
day = min(range(1, 6), key=lambda d: abs(line['x'] - columns[d])) if not columns: continue
if abs(line['x'] - columns[day]) >= step / 2 or line['y'] <= header_y: continue day = min(columns, key=lambda d: abs(line['x'] - columns[d]))
row = next((i for i in range(4) if bounds[i] <= line['y'] < bounds[i+1]), None) if abs(line['x'] - columns[day]) >= step/2 or line['y'] <= header_y: continue
if row is None: continue
text = compact(line['text']) text = compact(line['text'])
if not text: continue if not text or weekday(text) or re.fullmatch(r'\d{1,2}[::]\d{2}(?:[-—~~]\d{1,2}[::]\d{2})?',text): continue
cell = cells[(day, SLOTS[row]['id'])] row = next((i for i,(top,bottom) in rows.items() if top<=line['y']<bottom),None)
empty = text in ('无课', '空闲', '无课程') if row is None: continue
if empty: target_rows = [row]
if cell['status'] == 'unknown' and line['score'] >= .9: # 文本中明确的“3-6节”比文字中心位置可靠。
cell.update(status='free', confidence=line['score']) explicit = re.search(r'(?:第)?(\d{1,2})[-—~~至](\d{1,2})节',text)
if explicit and 1<=int(explicit[1])<=int(explicit[2])<=12:
target_rows = [i for i in rows if any(n in (i*2+1,i*2+2) for n in range(int(explicit[1]),int(explicit[2])+1))]
else: else:
cell['status'] = 'busy' block = next(((x1,y1,x2,y2) for x1,y1,x2,y2 in blocks
cell['courses'] = (cell['courses'] + '\n' + line['text']).strip()[:500] if x1<=line['x']<=x2 and y1<=line['y']<=y2 and step*.45<=x2-x1<=step*1.15
cell['confidence'] = min(cell['confidence'] or 1, line['score']) and y2-y1>=line['height']*1.5),None)
if block:
_,y1,_,y2=block
target_rows = [i for i,(top,bottom) in rows.items()
if min(y2,bottom)-max(y1,top)>min(y2-y1,bottom-top)*.2]
empty = text in ('无课', '空闲', '无课程')
for i in target_rows:
cell = cells[(day,SLOTS[i]['id'])]
if empty:
if cell['status']=='unknown' and line['score']>=.9:
cell.update(status='free',confidence=line['score'])
else:
# 低分文本提示核对,不能据此推断空闲。
cell['status']='busy'
if line['text'] not in cell['courses'].split('\n'):
cell['courses']=(cell['courses']+'\n'+line['text']).strip()[:500]
cell['confidence']=min(cell['confidence'] or 1,line['score'])
return result return result
def layout_lines(raw, blocks):
"""把表头和左侧节次拼成一张小图,只识别定位文字,跳过课程正文。"""
with Image.open(io.BytesIO(raw)) as image:
image=image.convert('RGB');width,height=image.size
cards=[b for b in blocks if width*.06<=b[2]-b[0]<=width*.85 and b[3]-b[1]>=height*.055]
if not cards: return []
table_top=int(min(b[1] for b in cards))
# 周一或上午可能完全无课,首个课程块不能直接当成表格左沿/表头下沿。
rail_right=int(min(min(b[0] for b in cards),width*.18))
if not width*.04<=rail_right<=width*.25: return []
if table_top>height*.3:
table_top=int(height*.3)
header_top=0
else:
header_top=max(0,table_top-int(width*.28))
crops=[(0,header_top,width,table_top)]
tile_height=440;gap=20
for top in range(table_top,height,tile_height-40):
crops.append((0,top,rail_right,min(top+tile_height,height)))
header_height=table_top-header_top
canvas=Image.new('RGB',(max(width,(rail_right+gap)*(len(crops)-1)),header_height+gap+tile_height),'white')
transforms=[]
for i,(x1,y1,x2,y2) in enumerate(crops):
dx,dy=(0,0) if i==0 else ((i-1)*(rail_right+gap),header_height+gap)
canvas.paste(image.crop((x1,y1,x2,y2)),(dx,dy))
transforms.append((dx,dy,dx+x2-x1,dy+y2-y1,x1-dx,y1-dy))
encoded=io.BytesIO();canvas.save(encoded,'PNG',compress_level=1)
mapped=[];seen=set()
for line in read_image(encoded.getvalue()):
x=median(p[0] for p in line['box']);y=median(p[1] for p in line['box'])
transform=next((t for t in transforms if t[0]<=x<t[2] and t[1]<=y<t[3]),None)
if transform:
ox,oy=transform[4:]
key=(line['text'],round(x+ox),round(y+oy))
if key in seen:continue
seen.add(key)
mapped.append({**line,'box':[[px+ox,py+oy] for px,py in line['box']]})
return mapped
def occupancy_from_blocks(lines, blocks, image_size):
"""完整定位的彩色周课表按课程块覆盖判断有课/无课,不依赖课程文字。"""
positioned=_positioned(lines);layout=_columns(positioned)
if not layout: return None
columns,step,header_y,inferred_days=layout
if len(columns)!=5 or len(inferred_days)>1: return None
rows,inferred_rows=_rows(positioned,min(columns.values())-step/2,header_y)
if len(rows)!=4 or inferred_rows:return None
width,height=image_size
if not width*.04<=columns[1]-step/2<=width*.25 or columns[5]+step/2>width:return None
# 一楼四个时段必须完整出现在截图中,裁切的末行不能被当作无课。
if min(top for top,_ in rows.values())<=header_y or max(bottom for _,bottom in rows.values())>height:
return None
cards=[]
for x1,y1,x2,y2 in blocks:
if y1<=header_y or y2-y1<min(bottom-top for top,bottom in rows.values())*.35:continue
if not step*.5<=x2-x1<=step*3.2:continue
if any(min(x2,x+step/2)-max(x1,x-step/2)>step*.5 for x in columns.values()):cards.append((x1,y1,x2,y2))
if not cards:return None
result=blank_structure()
result['method']='color_blocks'
result['warnings']=['已按彩色课程块整理有课/无课,跨节课程按覆盖时段记录。请对照原图核对后确认。']
for cell in result['cells']:
x=columns[cell['day']];top,bottom=rows[SLOT_INDEX[cell['slot']]]
busy=any(min(x2,x+step/2)-max(x1,x-step/2)>step*.5
and min(y2,bottom)-max(y1,top)>min(y2-y1,bottom-top)*.2 for x1,y1,x2,y2 in cards)
cell.update(status='busy' if busy else 'free',confidence=.95,source='image')
return result
SLOT_INDEX={slot['id']:i for i,slot in enumerate(SLOTS)}
def recognize(raw): def recognize(raw):
return structure_from_lines(read_image(raw)) started = time.perf_counter()
key = hashlib.sha256(raw).digest()
with _cache_lock:
cached = _cache.get(key)
if cached is not None:
_cache.move_to_end(key)
result = copy.deepcopy(cached)
result['recognition_ms']=round((time.perf_counter()-started)*1000)
result['cache_hit']=True
return result
blocks=course_blocks(raw)
lines=layout_lines(raw,blocks)
with Image.open(io.BytesIO(raw)) as image: size=image.size
result=occupancy_from_blocks(lines,blocks,size) if lines else None
if result is None:
result=structure_from_lines(read_image(raw),blocks)
result['method']='text_fallback'
result['warnings'].append('未能可靠定位彩色课表,未确定的位置请手动选择有课或无课。')
# 只保留时段占用状态,不收集课程名、教师及教室。
result['raw_text']=''
for cell in result['cells']:cell['courses']=''
result['recognition_ms']=round((time.perf_counter()-started)*1000)
result['cache_hit']=False
with _cache_lock:
_cache[key]=copy.deepcopy(result)
while len(_cache)>16: _cache.popitem(last=False)
return result
+1 -1
View File
@@ -151,7 +151,7 @@ def install(app, get_db, current_user, file_root, collector_emails):
@app.get('/api/timetables/schema') @app.get('/api/timetables/schema')
async def schema(viewer=Depends(current_user)): async def schema(viewer=Depends(current_user)):
return {'schema_version': 1, 'week_types': {'odd': '单周', 'even': '双周'}, 'days': ocr.DAYS, 'slots': ocr.SLOTS, return {'schema_version': 1, 'week_types': {'odd': '单周', 'even': '双周'}, 'days': ocr.DAYS, 'slots': ocr.SLOTS,
'states': {'busy': '有课', 'free': '空闲', 'unknown': '待确认'}, 'states': {'busy': '有课', 'free': '无课', 'unknown': '待确认'},
'export': '/api/timetables/export?format=json&confirmed_only=true', 'export': '/api/timetables/export?format=json&confirmed_only=true',
'privacy': '本人可导出自己的课表;收取负责人可导出全部;不包含邮箱和手机号', 'privacy': '本人可导出自己的课表;收取负责人可导出全部;不包含邮箱和手机号',
'eligibility': '仅已确认课表中的free时段可列为可值班;unknown不能当作空闲', 'eligibility': '仅已确认课表中的free时段可列为可值班;unknown不能当作空闲',
+88
View File
@@ -0,0 +1,88 @@
import io
import unittest
from unittest.mock import patch
from PIL import Image, ImageDraw
from server import timetable_ocr as ocr
def line(x, y, text, score=.99):
return {'box': [[x-12,y-8],[x+12,y-8],[x+12,y+8],[x-12,y+8]], 'text':text, 'score':score}
def headers():
return ([line(120+80*i,100,word) for i,word in enumerate('一二三四五六日')]
+ [line(35,160+40*i,str(i+1)) for i in range(10)])
def sample_image():
image=Image.new('RGB',(680,600),'white');draw=ImageDraw.Draw(image)
draw.rectangle((165,142,235,298),fill='#89a66d') # 周二一至四节
draw.rectangle((85,382,155,458),fill='#8ba3fc') # 周一七八节
draw.rectangle((165,302,235,378),fill='#8ed7ed')
draw.rectangle((245,302,315,378),fill='#f66f6f') # 紧贴区域按颜色分割
draw.rectangle((165,382,315,458),fill='#f66f6f') # 同色两列,分别计入
draw.rectangle((405,462,475,538),fill='#82be54') # 周五晚课,不计入七八节
raw=io.BytesIO();image.save(raw,'PNG');return raw.getvalue()
class TimetableOccupancyTests(unittest.TestCase):
def setUp(self):
with ocr._cache_lock:ocr._cache.clear()
def test_colored_blocks_include_cross_periods_split_adjacent_days_and_skip_evening(self):
raw=sample_image();blocks=ocr.course_blocks(raw)
result=ocr.occupancy_from_blocks(headers(),blocks,(680,600))
self.assertIsNotNone(result)
cells={(c['day'],c['slot']):c for c in result['cells']}
expected={(2,'1-2'),(2,'3-4'),(2,'5-6'),(3,'5-6'),(1,'7-8'),(2,'7-8'),(3,'7-8')}
self.assertEqual({key for key,c in cells.items() if c['status']=='busy'},expected)
self.assertTrue(all(c['status'] in ('busy','free') for c in cells.values()))
def test_one_missing_weekday_and_spurious_header_fragment_do_not_shift_columns(self):
raw=sample_image();blocks=ocr.course_blocks(raw)
complete=ocr.occupancy_from_blocks(headers(),blocks,(680,600))
missing=[l for l in headers() if l['text']!='一']
self.assertEqual(ocr.occupancy_from_blocks(missing,blocks,(680,600))['cells'],complete['cells'])
fragmented=headers()+[line(200,110,'一',.7)]
self.assertEqual(ocr.occupancy_from_blocks(fragmented,blocks,(680,600))['cells'],complete['cells'])
def test_partial_cropped_or_unlocated_table_never_invents_free_slots(self):
blocks=ocr.course_blocks(sample_image())
self.assertIsNone(ocr.occupancy_from_blocks([],blocks,(680,600)))
self.assertIsNone(ocr.occupancy_from_blocks(headers(),blocks,(680,400)))
incomplete=[l for l in headers() if l['text'] not in ('7','8')]
self.assertIsNone(ocr.occupancy_from_blocks(incomplete,blocks,(680,600)))
def test_evening_number_misread_as_six_does_not_shift_afternoon_rows(self):
blocks=ocr.course_blocks(sample_image())
normal=ocr.occupancy_from_blocks(headers(),blocks,(680,600))
mistaken=[l for l in headers() if l['text']!='9']+[line(35,480,'6')]
result=ocr.occupancy_from_blocks(mistaken,blocks,(680,600))
self.assertEqual(result['cells'],normal['cells'])
def test_layout_extraction_still_runs_when_monday_and_morning_are_empty(self):
image=Image.new('RGB',(680,900),'white');draw=ImageDraw.Draw(image)
draw.rectangle((325,500,395,650),fill='#8ba3fc')
raw=io.BytesIO();image.save(raw,'PNG');raw=raw.getvalue()
with patch.object(ocr,'read_image',return_value=[]) as reader:
ocr.layout_lines(raw,ocr.course_blocks(raw))
reader.assert_called_once()
def test_fast_path_skips_course_text_and_cache_returns_independent_results(self):
raw=sample_image()
with patch.object(ocr,'layout_lines',return_value=headers()) as layout,patch.object(ocr,'read_image') as full_ocr:
first=ocr.recognize(raw)
self.assertEqual(first['method'],'color_blocks');self.assertFalse(first['cache_hit'])
self.assertEqual(first['raw_text'],'');self.assertTrue(all(c['courses']=='' for c in first['cells']))
first['cells'][0]['status']='changed'
second=ocr.recognize(raw)
self.assertTrue(second['cache_hit']);self.assertNotEqual(second['cells'][0]['status'],'changed')
layout.assert_called_once();full_ocr.assert_not_called()
def test_missing_layout_falls_back_without_retaining_course_names(self):
with patch.object(ocr,'layout_lines',return_value=[]),patch.object(ocr,'read_image',return_value=[line(120,200,'测试课程')]):
result=ocr.recognize(sample_image())
self.assertEqual(result['method'],'text_fallback')
self.assertTrue(all(c['status']=='unknown' and c['courses']=='' for c in result['cells']))
self.assertEqual(result['raw_text'],'')