Files
worklog/server/timetable_ocr.py
T

150 lines
6.9 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 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))