Files
worklog/server/timetable_ocr.py
T

379 lines
18 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""本地图片识别及值班时段整理。留白保持待确认,不能直接当作空闲。"""
import io
import copy
import hashlib
import time
from collections import OrderedDict
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()
_cache = OrderedDict()
_cache_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', compress_level=1)
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': 2000,
'Det.limit_side_len': 1600, 'Det.limit_type': 'max',
'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)
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)
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('第', '')
value = re.sub(r'[—–-~~至]', '-', value)
# 时间、周次和课程名中的数字不能当作节次。
value = re.split(r'节|[((\[]|\n', value, maxsplit=1)[0]
chinese = {word: i for i, word in enumerate(('一','二','三','四','五','六','七','八','九','十','十一','十二'), 1)}
if value in chinese: return [chinese[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 []
start = int(match[1]); end = int(match[2] or start)
return list(range(start, end + 1)) if 1 <= start <= end <= 12 else []
def _positioned(lines):
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,
'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'])]
candidates = []
for header in headers:
group = [line for line in headers if abs(line['y'] - header['y']) < max(15, header['height'] * 1.5)]
columns = {}
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}
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))
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}
section_y = {}
for line in positioned:
if line['x'] >= left or line['y'] <= header_y: continue
nums = periods(line['text'])
if nums:
for number in nums:
section_y.setdefault(number, []).append(line['y'])
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']).replace(':', ':')
for slot in SLOTS:
if re.match(r'^0?' + re.escape(slot['start'].lstrip('0')) + r'(?:$|[-~~—])', value):
# 有节次文字时优先节次,避免小号时间标签拉偏行中心。
if not anchors[slot['id']]: anchors[slot['id']].append(line['y'])
# 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
columns, step, header_y, inferred_days = layout
if inferred_days:
result['warnings'].append('部分星期文字未识别,已参考相邻列定位;请重点核对。')
left = min(columns.values()) - step/2
rows, inferred_rows = _rows(positioned,left,header_y)
if len(rows)<4:
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']}
for line in sorted(positioned,key=lambda line:(line['y'],line['x'])):
if not columns: continue
day = min(columns, key=lambda d: abs(line['x'] - columns[d]))
if abs(line['x'] - columns[day]) >= step/2 or line['y'] <= header_y: continue
text = compact(line['text'])
if not text or weekday(text) or re.fullmatch(r'\d{1,2}[::]\d{2}(?:[-—~~]\d{1,2}[::]\d{2})?',text): continue
row = next((i for i,(top,bottom) in rows.items() if top<=line['y']<bottom),None)
if row is None: continue
target_rows = [row]
# 文本中明确的“3-6节”比文字中心位置可靠。
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:
block = next(((x1,y1,x2,y2) for x1,y1,x2,y2 in blocks
if x1<=line['x']<=x2 and y1<=line['y']<=y2 and step*.45<=x2-x1<=step*1.15
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
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):
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