From 2fb2c5e1add01d83a2fc45cca4839896bf31bbad Mon Sep 17 00:00:00 2001 From: soehi <811446351@qq.com> Date: Fri, 13 Nov 2026 14:35:28 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E8=AF=BE=E8=A1=A8=E8=AF=86?= =?UTF-8?q?=E5=88=AB=E5=B9=B6=E6=94=AF=E6=8C=81=E9=87=8D=E6=96=B0=E8=AF=86?= =?UTF-8?q?=E5=88=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TIMETABLES.md | 9 ++- server/timetable_ocr.py | 118 +++++++++++++++++++++++++----- server/timetables.py | 63 ++++++++++++++-- tests/test_timetable_occupancy.py | 13 +++- tests/test_timetables.py | 27 ++++++- 5 files changed, 199 insertions(+), 31 deletions(-) diff --git a/TIMETABLES.md b/TIMETABLES.md index 6c50619..1950a8d 100644 --- a/TIMETABLES.md +++ b/TIMETABLES.md @@ -8,7 +8,7 @@ ## 自动整理与核对 -安装 `requirements.txt`(RapidOCR、ONNX Runtime)即可在服务器本地处理图片,不需要外部识别服务账号,也不发送课表到外部平台。对常见彩色周课表,先提取课程块,再把星期表头和左侧节次拼为小图识别,只读取定位文字;跨多节、贴边或相同颜色相邻课程按日期列及覆盖时段分别计入。JPG色差通过重叠色域和形态学处理缓解。支持“一、二、三”等单字星期表头,以及单节、双节和时间标签。 +安装 `requirements.txt`(RapidOCR、ONNX Runtime)即可在服务器本地处理图片,不需要外部识别服务账号,也不发送课表到外部平台。对常见彩色周课表,先定位星期和节次,再直接统计每个网格内的彩色课程卡片覆盖率;相邻日期、相同颜色和跨节课程均逐格判断,不再依赖连接在一起的课程块。OCR 只识别上方星期和左侧时间的定位小图,不读取课程正文,因此速度更快,也不受课程名、教师和教室文字影响。支持“一、二、三”等单字星期表头、`11月16一` 这类日期星期连写,以及节次和时间标签;月份标签和周一字符合并识别时会用其余星期位置拟合并还原。JPG 色差通过饱和度和明度阈值缓解。 每次推理最多两个CPU线程,检测图长边限制为1600像素,避免长截图按短边放大造成额外计算。服务进程保留最近16张相同图片的解析缓存,仅保存结构结果,不保留额外图片副本;重试、重复提交单双周同一张图可复用结果。结果独立复制,校对不会修改缓存。首次加载模型仍比后续慢。 @@ -23,7 +23,7 @@ | `5-6` | 五六节 | 14:00–15:45 | | `7-8` | 七八节 | 16:00–17:45 | -程序根据星期列、节次以及课程块覆盖范围整理周一至周五20个时段。完整定位的彩色课表可根据留白建议“无课”,仅保存 `busy` / `free`;课程名、教师、教室和识别原文留空。表格未完整展示、缺少可靠定位或不是彩色课表时,回退文字位置判断,无法确定的时段保持 `unknown`,不会把识别失败当作无课。节次与星期仅有少量漏字时可参考相邻标签定位;边界或行位置不可靠则交由本人核对。晚间和周末课程不参与当前四个值班时段判断。 +程序根据星期列、节次以及课程卡片覆盖率整理周一至周五20个时段。完整定位的彩色课表仅保存 `busy` / `free`;课程名、教师、教室和识别原文留空。表格未完整展示、缺少可靠定位或不是彩色课表时,回退课程块或文字位置判断,无法确定的时段保持 `unknown`,不会把识别失败当作无课。星期轴允许一个异常或漏识别列,完整七日历表头会用其余列拟合补齐;四行值班时段必须全部可靠定位。边界或行位置不可靠则交由本人核对。晚间和周末课程不参与当前四个值班时段判断。 校对页面默认缩小显示完整原图,校对表先收起。点击“校对课表”后,在原图上显示透明底板与透明单元格的校对按钮层,原图保持原色;点击时段按钮即可切换“有课 / 无课”,定位失败时保留“待确认”。有课按钮用红色文字和边框标注,保存操作位于图片下方,避免遮挡课表。可点“看清原图”临时隐藏全部标注,再点“恢复校对标注”继续;也可随时收起校对层或放大原图;收起、放大不丢失当前修改。界面显示有课、无课及待确认时段数,不再要求填写课程备注。核对后可将其余待确认设为无课。保存草稿不等于确认;只有20个时段均已明确,才能点击“核对无误并确认”。识别组件异常时仍保存图片并提供手动整理。自动结果始终需要核对,只有已确认的无课时段才可供排班使用。 @@ -37,7 +37,7 @@ ## 程序读取与导出 -所有接口均需要 `Authorization: Bearer <登录会话令牌>`;导出接口还必须提供 `X-Timetable-Admin-Key: <管理员密钥>`。 +所有接口均需要 `Authorization: Bearer <登录会话令牌>`;导出和重新识别接口还必须提供 `X-Timetable-Admin-Key: <管理员密钥>`。 | 接口 | 用途 | | --- | --- | @@ -49,9 +49,12 @@ | `GET /api/timetables/schema` | 周次、时段、状态、权限及可值班规则说明 | | `GET /api/timetables/export?format=json` | 完整结构,适合程序和AI读取 | | `GET /api/timetables/export?format=csv` | 每个课表20行,便于表格整理 | +| `POST /api/timetables/reprocess` | 管理员选择 `user_ids`、`week_types`,用当前算法重跑已保存图片;默认跳过已人工确认的课表 | 默认 `confirmed_only=false`,未核对课表和已核对课表都会导出;传 `true` 可只导出已核对课表。管理员密钥正确时导出全部成员,密钥错误或缺失时拒绝下载。JSON 中 `structure.cells` 每项包含 `day=1..5`、`slot`、`status=busy/free/unknown`、`courses`、`confidence`、`source` 和 `eligible`。时段时间见顶层 `slots`,记录的 `week_type` 为 `odd` / `even`。时间戳为 Unix 毫秒。 +重新识别接口只更新结构化结果和修订时间,不替换或删除原图。已人工确认的记录默认返回 `skipped_confirmed`;只有请求显式传入 `force_confirmed=true` 才会覆盖并撤销确认。 + **排班时必须使用 `eligible=true` 的时段**,即课表已确认且该时段明确为空闲;没有上传、未核对、未知时段都不能视为有空。JSON 包含核对时间及整理结果,不以原图下载链接的可访问性判断空闲。CSV 为 UTF-8 BOM,保护可能被电子表格当作公式的文本内容。 ## 部署和备份 diff --git a/server/timetable_ocr.py b/server/timetable_ocr.py index f9ff7b7..c9c8ce1 100644 --- a/server/timetable_ocr.py +++ b/server/timetable_ocr.py @@ -71,10 +71,16 @@ def weekday(text): return 7 if value in '日天' else '一二三四五六'.index(value)+1 if value in ('-', '—', '一'): return 1 - match = re.match(r'^(?:星期|礼拜|周)([一二三四五六日天1-7])', value) + match = re.search(r'(?:星期|礼拜|周)([一二三四五六日天1-7])$', value) if match: token = match[1] return int(token) if token.isdigit() else 7 if token in '日天' else '一二三四五六'.index(token) + 1 + # 教务系统常把日期和星期合成“11月16一”“10二”一行。 + # 只接受以日期结尾、最后一个字为星期汉字的紧凑表头,避免把课程名当表头。 + match = re.search(r'\d{1,2}\s*[月./-]?\s*\d{0,2}\s*([一二三四五六日天])$', value) + if match: + token = match[1] + return 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 @@ -111,27 +117,46 @@ def _columns(positioned): candidates = [] for header in headers: group = [line for line in headers if abs(line['y'] - header['y']) < max(15, header['height'] * 1.5)] - columns = {} + observed = {} for line in group: - columns.setdefault(weekday(line['text']), []).append(line['x']) - unique = {day:xs[0] for day,xs in columns.items() if len(xs)==1} + observed.setdefault(weekday(line['text']), []).append(line['x']) + unique = {day: median(xs) for day,xs in observed.items()} days = sorted(unique) - if len(days)>=3: - guessed_step=median((unique[b]-unique[a])/(b-a) for a,b in zip(days,days[1:])) - origin=median(unique[d]-(d-1)*guessed_step for d in days) - 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)) + + # “11月”月份标签常与周一格合并识别,导致周一锚点明显偏左。 + # 用两两锚点拟合,选内点最多的一条等距星期轴,再内插异常或漏字的一列。 + line_height = median(line['height'] for line in group) + base_tolerance = max(18, line_height * .8) + fit = None + for position, first_day in enumerate(days): + for last_day in days[position + 1:]: + step = (unique[last_day] - unique[first_day]) / (last_day - first_day) + if step <= 0: continue + origin = unique[first_day] - (first_day - 1) * step + tolerance = max(base_tolerance, step * .18) + inliers = [day for day in days + if abs(unique[day] - (origin + (day - 1) * step)) <= tolerance] + if len(inliers) < 5: continue + error = sum(abs(unique[day] - (origin + (day - 1) * step)) for day in inliers) / len(inliers) + score = (len(inliers), -error, -step) + if fit is None or score > fit[0]: + fit = (score, origin, step, inliers) + if fit is None: continue + _, origin, step, inliers = fit + columns = { + day: unique[day] if day in inliers else origin + (day - 1) * step + for day in days + } + # 完整的七日历表头允许内插一个漏识别列;首尾之外不凭空扩展。 + for day in range(min(days), max(days) + 1): + columns.setdefault(day, origin + (day - 1) * step) + inferred = [day for day in columns if day not in inliers] + candidates.append((len(inliers), -median(line['y'] for line in group), + origin, step, columns, group, inferred)) 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] + _, _, origin, step, columns, group, inferred = max(candidates, key=lambda item: item[:2]) + inferred = sorted(set(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)} @@ -348,6 +373,59 @@ def occupancy_from_blocks(lines, blocks, image_size): SLOT_INDEX={slot['id']:i for i,slot in enumerate(SLOTS)} +def occupancy_from_grid(lines, raw, image_size): + """按课表网格直接统计每格彩色卡片覆盖率,跨节和相邻课程都逐格判断。""" + import cv2 + import numpy as np + + 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 + left = columns[1] - step / 2 + right = columns[5] + step / 2 + if not width * .04 <= left <= width * .25 or right > width + step * .05: return None + # 只分析四个完整值班时段;截掉的表头、周次或末行都不能制造“无课”。 + if min(top for top, _ in rows.values()) <= header_y or max(bottom for _, bottom in rows.values()) > height: + return None + + with Image.open(io.BytesIO(raw)) as image: + rgb = np.array(image.convert('RGB')) + hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV) + saturation, brightness = hsv[:, :, 1], hsv[:, :, 2] + colored = (saturation >= 28) & (brightness >= 105) + result = blank_structure() + result['method'] = 'color_grid' + result['warnings'] = ['已按课表彩色课程卡片逐格整理有课/无课,跨节课程按覆盖时段记录。请对照原图核对后确认。'] + coverages = [] + for cell in result['cells']: + slot_index = SLOT_INDEX[cell['slot']] + center_x = columns[cell['day']] + top, bottom = rows[slot_index] + # 留出网格线和卡片圆角,取单元格内部 80%×84% 的区域判断。 + x1 = max(0, int(center_x - step * .40)) + x2 = min(width, int(center_x + step * .40)) + y1 = max(0, int(top + (bottom - top) * .08)) + y2 = min(height, int(bottom - (bottom - top) * .08)) + sample = colored[y1:y2, x1:x2] + coverage = float(sample.mean()) if sample.size else 0.0 + coverages.append(coverage) + busy = coverage >= .14 + cell.update( + status='busy' if busy else 'free', + confidence=round(min(.99, .78 + coverage * .22) if busy else min(.99, .99 - coverage), 3), + source='image', + ) + # 网格完整但所有格子都没有彩色卡片,说明更像截图区域选错,不能整表判为空闲。 + if max(coverages, default=0) < .14: + return None + return result + + def recognize(raw): started = time.perf_counter() key = hashlib.sha256(raw).digest() @@ -362,7 +440,9 @@ def recognize(raw): 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 + result=occupancy_from_grid(lines,raw,size) if lines else None + if result is None: + 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' diff --git a/server/timetables.py b/server/timetables.py index eea59e7..8348032 100644 --- a/server/timetables.py +++ b/server/timetables.py @@ -12,7 +12,7 @@ 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 import select, text, update from sqlalchemy.dialects.sqlite import insert from .models import timetables, users @@ -36,6 +36,12 @@ class Correction(BaseModel): confirm: bool = False +class ReprocessSelection(BaseModel): + user_ids: list[str] = Field(min_length=1, max_length=100) + week_types: list[Week] = Field(default_factory=lambda: ['odd', 'even'], min_length=1, max_length=2) + force_confirmed: bool = False + + def now_ms(): return int(time.time() * 1000) @@ -60,6 +66,14 @@ def install(app, get_db, current_user, file_root, collector_emails, admin_key): if not row: raise HTTPException(404, '课表尚未上传') return row + def require_admin(request): + expected = admin_key() + supplied = request.headers.get('X-Timetable-Admin-Key', '') + if not expected: + raise HTTPException(503, '课表管理员密钥尚未配置') + if not supplied or not secrets.compare_digest(supplied.encode('utf-8'), expected.encode('utf-8')): + raise HTTPException(401, '管理员密钥错误') + @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)): @@ -162,12 +176,7 @@ def install(app, get_db, current_user, file_root, collector_emails, admin_key): @app.get('/api/timetables/export') async def export(request: Request, format: Literal['json', 'csv'] = 'json', confirmed_only: bool = False, db=Depends(get_db), viewer=Depends(current_user)): - expected = admin_key() - supplied = request.headers.get('X-Timetable-Admin-Key', '') - if not expected: - raise HTTPException(503, '课表导出管理员密钥尚未配置') - if not supplied or not secrets.compare_digest(supplied.encode('utf-8'), expected.encode('utf-8')): - raise HTTPException(401, '管理员密钥错误') + require_admin(request) 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 confirmed_only: query = query.where(timetables.c.confirmed_at.is_not(None)) found = (await db.execute(query)).mappings().all() @@ -194,6 +203,46 @@ def install(app, get_db, current_user, file_root, collector_emails, admin_key): 'Cache-Control': 'no-store', }) + @app.post('/api/timetables/reprocess') + async def reprocess(request: Request, payload: ReprocessSelection, db=Depends(get_db), viewer=Depends(current_user)): + """管理员用新算法重跑已保存图片;默认不覆盖人工已确认课表。""" + require_admin(request) + user_ids = list(dict.fromkeys(payload.user_ids)) + weeks = list(dict.fromkeys(payload.week_types)) + found = (await db.execute( + select(timetables).where(timetables.c.user_id.in_(user_ids), timetables.c.week_type.in_(weeks)) + .order_by(timetables.c.user_id, timetables.c.week_type) + )).mappings().all() + results = [] + for row in found: + if row['confirmed_at'] and not payload.force_confirmed: + results.append({'user_id': row['user_id'], 'week_type': row['week_type'], + 'status': 'skipped_confirmed', 'revision': public_file(row)['revision']}) + continue + path = file_root() / row['file_key'] + if not path.is_file(): + results.append({'user_id': row['user_id'], 'week_type': row['week_type'], 'status': 'missing_file'}) + continue + try: + image = await asyncio.to_thread(ocr.normalize_image, await asyncio.to_thread(path.read_bytes)) + async with _recognition_slots: + structure = await asyncio.to_thread(ocr.recognize, image) + except Exception: + results.append({'user_id': row['user_id'], 'week_type': row['week_type'], 'status': 'recognition_failed'}) + continue + stamp = max(now_ms(), row['updated_at'] + 1) + await db.execute(update(timetables).where( + timetables.c.user_id == row['user_id'], timetables.c.week_type == row['week_type'] + ).values( + structure=json.dumps(structure, ensure_ascii=False), + ocr_status='needs_review', updated_at=stamp, confirmed_at=None, + )) + results.append({'user_id': row['user_id'], 'week_type': row['week_type'], 'status': 'recognized', + 'revision': row['file_key'] + ':' + str(stamp), 'method': structure.get('method'), + 'unknown': sum(cell['status'] == 'unknown' for cell in structure['cells'])}) + await db.commit() + return {'processed': len(results), 'results': results} + @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))} diff --git a/tests/test_timetable_occupancy.py b/tests/test_timetable_occupancy.py index 88fd438..c6b2ee3 100644 --- a/tests/test_timetable_occupancy.py +++ b/tests/test_timetable_occupancy.py @@ -61,6 +61,17 @@ class TimetableOccupancyTests(unittest.TestCase): result=ocr.occupancy_from_blocks(mistaken,blocks,(680,600)) self.assertEqual(result['cells'],normal['cells']) + def test_grid_handles_month_label_merged_into_monday_header(self): + raw=sample_image() + complete=ocr.occupancy_from_grid(headers(),raw,(680,600)) + compact = [line(55,100,'11月16一')] + [ + line(200+80*i,100,f'{17+i}{weekday}') for i,weekday in enumerate('二三四五六日') + ] + [line(35,160+40*i,str(i+1)) for i in range(10)] + result=ocr.occupancy_from_grid(compact,raw,(680,600)) + self.assertIsNotNone(result) + self.assertEqual(result['method'],'color_grid') + self.assertEqual(result['cells'],complete['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') @@ -73,7 +84,7 @@ class TimetableOccupancyTests(unittest.TestCase): 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['method'],'color_grid');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) diff --git a/tests/test_timetables.py b/tests/test_timetables.py index 35c7a45..2deadf2 100644 --- a/tests/test_timetables.py +++ b/tests/test_timetables.py @@ -10,7 +10,7 @@ from pathlib import Path from unittest.mock import patch from PIL import Image -from sqlalchemy import select, func +from sqlalchemy import select, func, update from server import timetable_ocr as ocr from server.models import timetables from test_api import ApiTestCase, auth, register @@ -162,6 +162,31 @@ class TimetableTests(ApiTestCase): 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_admin_can_reprocess_saved_images_without_overwriting_confirmed_rows(self): + user = await register(self.client,'timetablereprocess') + item = await self.upload(user) + async with self.sessions() as db: + await db.execute(update(timetables).where( + timetables.c.user_id == user['user']['id'], timetables.c.week_type == 'odd' + ).values(structure=json.dumps(ocr.blank_structure()),ocr_status='needs_review')) + await db.commit() + endpoint='/api/timetables/reprocess' + payload={'user_ids':[user['user']['id']],'week_types':['odd']} + self.assertEqual((await self.client.post(endpoint,headers=auth(user['token']),json=payload)).status_code,401) + denied=await self.client.post(endpoint,headers=self.export_headers(user,'wrong-key'),json=payload) + self.assertEqual(denied.status_code,401) + result=await self.client.post(endpoint,headers=self.export_headers(user),json=payload) + self.assertEqual(result.status_code,200,result.text) + self.assertEqual(result.json()['results'][0]['status'],'recognized') + detail=(await self.client.get('/api/timetables/'+user['user']['id']+'/odd',headers=auth(user['token']))).json()['timetable'] + self.assertEqual(detail['structure']['cells'][0]['status'],'busy') + self.assertNotEqual(detail['revision'],item['revision']) + + confirmed=await self.confirm(user,detail) + self.assertEqual(confirmed.status_code,200,confirmed.text) + skipped=await self.client.post(endpoint,headers=self.export_headers(user),json=payload) + self.assertEqual(skipped.json()['results'][0]['status'],'skipped_confirmed') + 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: