优化课表识别并支持重新识别
This commit is contained in:
+56
-7
@@ -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))}
|
||||
|
||||
Reference in New Issue
Block a user