新增单双周课表图片收取、本地识别校对及排班数据导出
This commit is contained in:
@@ -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)
|
||||
Reference in New Issue
Block a user