- Deleted obsolete markdown files related to follow tab coordinates testing and results. - Removed outdated batch scripts for launching the Web GUI. - Updated `config.json` to improve reservation handling and adjust prize value settings. - Enhanced logging and error handling in `web_gui.py` and `app.js` for better user experience. - Added automatic screenshot functionality during Web GUI startup for improved monitoring.
376 lines
12 KiB
Python
376 lines
12 KiB
Python
"""
|
|
OCR优化模块:支持多种OCR方案,可配置切换
|
|
|
|
支持的方案:
|
|
1. PaddleOCR(当前默认,准确但较慢)
|
|
2. EasyOCR(推荐,快速且准确)
|
|
3. 百度OCR API(在线,极快极准,有免费额度)
|
|
4. 腾讯OCR API(在线,极快极准,有免费额度)
|
|
|
|
使用方法:
|
|
1. 设置环境变量 OCR_TYPE=easyocr 或 baidu 或 tencent
|
|
2. 或在 config.json 中设置 "ocr_type": "easyocr"
|
|
"""
|
|
|
|
import os
|
|
import base64
|
|
import json
|
|
import time
|
|
from typing import Optional, Tuple
|
|
from PIL import Image
|
|
import numpy as np
|
|
|
|
|
|
class OCRProvider:
|
|
"""OCR提供者基类"""
|
|
|
|
def __init__(self):
|
|
self.initialized = False
|
|
self.provider = None
|
|
|
|
def initialize(self):
|
|
"""初始化OCR引擎"""
|
|
raise NotImplementedError
|
|
|
|
def recognize(self, image: Image.Image) -> str:
|
|
"""识别图片中的文字"""
|
|
raise NotImplementedError
|
|
|
|
|
|
class PaddleOCRProvider(OCRProvider):
|
|
"""PaddleOCR提供者(当前默认)"""
|
|
|
|
def initialize(self):
|
|
if self.initialized:
|
|
return
|
|
try:
|
|
import contextlib
|
|
devnull = open(os.devnull, "w")
|
|
with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(devnull):
|
|
from paddleocr import PaddleOCR
|
|
self.provider = PaddleOCR(
|
|
lang="ch",
|
|
ocr_version="PP-OCRv4",
|
|
use_doc_orientation_classify=False,
|
|
use_doc_unwarping=False,
|
|
use_textline_orientation=False,
|
|
)
|
|
devnull.close()
|
|
self.initialized = True
|
|
except Exception as e:
|
|
print(f"[OCR] PaddleOCR初始化失败: {e}")
|
|
self.provider = None
|
|
|
|
def recognize(self, image: Image.Image) -> str:
|
|
if not self.initialized:
|
|
self.initialize()
|
|
if self.provider is None:
|
|
return ""
|
|
|
|
try:
|
|
img_np = np.array(image.convert('RGB'))
|
|
result = self.provider.ocr(img_np)
|
|
if result == [None]:
|
|
return ""
|
|
|
|
# 提取文本
|
|
texts = []
|
|
if isinstance(result, list):
|
|
for item in result:
|
|
if isinstance(item, list):
|
|
for sub_item in item:
|
|
if isinstance(sub_item, (list, tuple)) and len(sub_item) >= 2:
|
|
text = sub_item[1]
|
|
if isinstance(text, (list, tuple)) and len(text) >= 1:
|
|
texts.append(str(text[0]))
|
|
elif isinstance(text, str):
|
|
texts.append(text)
|
|
elif isinstance(text, dict):
|
|
texts.append(str(text.get("text", text.get("rec_text", ""))))
|
|
|
|
return "".join(texts)
|
|
except Exception as e:
|
|
print(f"[OCR] PaddleOCR识别失败: {e}")
|
|
return ""
|
|
|
|
|
|
class EasyOCRProvider(OCRProvider):
|
|
"""EasyOCR提供者(推荐:快速且准确)"""
|
|
|
|
def initialize(self):
|
|
if self.initialized:
|
|
return
|
|
try:
|
|
import easyocr
|
|
# 只加载中文和英文,加快初始化速度
|
|
self.provider = easyocr.Reader(['ch_sim', 'en'], gpu=False) # gpu=True 如果可用GPU
|
|
self.initialized = True
|
|
print("[OCR] EasyOCR初始化成功")
|
|
except Exception as e:
|
|
print(f"[OCR] EasyOCR初始化失败: {e}")
|
|
print("[OCR] 请安装: pip install easyocr")
|
|
self.provider = None
|
|
|
|
def recognize(self, image: Image.Image) -> str:
|
|
if not self.initialized:
|
|
self.initialize()
|
|
if self.provider is None:
|
|
return ""
|
|
|
|
try:
|
|
img_np = np.array(image.convert('RGB'))
|
|
results = self.provider.readtext(img_np)
|
|
|
|
# EasyOCR返回格式: [(bbox, text, confidence), ...]
|
|
texts = [result[1] for result in results if len(result) >= 2]
|
|
return "".join(texts)
|
|
except Exception as e:
|
|
print(f"[OCR] EasyOCR识别失败: {e}")
|
|
return ""
|
|
|
|
|
|
class BaiduOCRProvider(OCRProvider):
|
|
"""百度OCR API提供者(在线,极快极准)"""
|
|
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.api_key = os.environ.get("BAIDU_OCR_API_KEY", "")
|
|
self.secret_key = os.environ.get("BAIDU_OCR_SECRET_KEY", "")
|
|
self.access_token = None
|
|
|
|
def initialize(self):
|
|
if self.initialized:
|
|
return
|
|
if not self.api_key or not self.secret_key:
|
|
print("[OCR] 百度OCR API: 未设置API_KEY和SECRET_KEY")
|
|
print("[OCR] 请设置环境变量: BAIDU_OCR_API_KEY 和 BAIDU_OCR_SECRET_KEY")
|
|
print("[OCR] 或访问: https://ai.baidu.com/tech/ocr/general")
|
|
return
|
|
|
|
try:
|
|
import requests
|
|
# 获取access_token
|
|
token_url = "https://aip.baidubce.com/oauth/2.0/token"
|
|
params = {
|
|
"grant_type": "client_credentials",
|
|
"client_id": self.api_key,
|
|
"client_secret": self.secret_key
|
|
}
|
|
response = requests.post(token_url, params=params, timeout=5)
|
|
if response.status_code == 200:
|
|
self.access_token = response.json().get("access_token")
|
|
self.initialized = True
|
|
print("[OCR] 百度OCR API初始化成功")
|
|
else:
|
|
print(f"[OCR] 百度OCR API获取token失败: {response.text}")
|
|
except Exception as e:
|
|
print(f"[OCR] 百度OCR API初始化失败: {e}")
|
|
|
|
def recognize(self, image: Image.Image) -> str:
|
|
if not self.initialized or not self.access_token:
|
|
return ""
|
|
|
|
try:
|
|
import requests
|
|
# 将图片转换为base64
|
|
from io import BytesIO
|
|
buffer = BytesIO()
|
|
image.save(buffer, format='PNG')
|
|
img_base64 = base64.b64encode(buffer.getvalue()).decode()
|
|
|
|
# 调用API
|
|
url = f"https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token={self.access_token}"
|
|
headers = {"Content-Type": "application/x-www-form-urlencoded"}
|
|
data = {"image": img_base64}
|
|
|
|
response = requests.post(url, headers=headers, data=data, timeout=5)
|
|
if response.status_code == 200:
|
|
result = response.json()
|
|
if "words_result" in result:
|
|
texts = [item.get("words", "") for item in result["words_result"]]
|
|
return "".join(texts)
|
|
return ""
|
|
except Exception as e:
|
|
print(f"[OCR] 百度OCR API识别失败: {e}")
|
|
return ""
|
|
|
|
|
|
class TencentOCRProvider(OCRProvider):
|
|
"""腾讯OCR API提供者(在线,极快极准)"""
|
|
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.secret_id = os.environ.get("TENCENT_OCR_SECRET_ID", "")
|
|
self.secret_key = os.environ.get("TENCENT_OCR_SECRET_KEY", "")
|
|
|
|
def initialize(self):
|
|
if self.initialized:
|
|
return
|
|
if not self.secret_id or not self.secret_key:
|
|
print("[OCR] 腾讯OCR API: 未设置SECRET_ID和SECRET_KEY")
|
|
print("[OCR] 请设置环境变量: TENCENT_OCR_SECRET_ID 和 TENCENT_OCR_SECRET_KEY")
|
|
return
|
|
|
|
try:
|
|
from tencentcloud.common import credential
|
|
from tencentcloud.common.profile.client_profile import ClientProfile
|
|
from tencentcloud.common.profile.http_profile import HttpProfile
|
|
from tencentcloud.ocr.v20181119 import ocr_client, models
|
|
|
|
cred = credential.Credential(self.secret_id, self.secret_key)
|
|
httpProfile = HttpProfile()
|
|
httpProfile.endpoint = "ocr.tencentcloudapi.com"
|
|
clientProfile = ClientProfile()
|
|
clientProfile.httpProfile = httpProfile
|
|
|
|
self.provider = ocr_client.OcrClient(cred, "ap-beijing", clientProfile)
|
|
self.models = models
|
|
self.initialized = True
|
|
print("[OCR] 腾讯OCR API初始化成功")
|
|
except Exception as e:
|
|
print(f"[OCR] 腾讯OCR API初始化失败: {e}")
|
|
print("[OCR] 请安装: pip install tencentcloud-sdk-python")
|
|
self.provider = None
|
|
|
|
def recognize(self, image: Image.Image) -> str:
|
|
if not self.initialized or self.provider is None:
|
|
return ""
|
|
|
|
try:
|
|
# 将图片转换为base64
|
|
from io import BytesIO
|
|
buffer = BytesIO()
|
|
image.save(buffer, format='PNG')
|
|
img_base64 = base64.b64encode(buffer.getvalue()).decode()
|
|
|
|
# 调用API
|
|
req = self.models.GeneralBasicOCRRequest()
|
|
req.ImageBase64 = img_base64
|
|
|
|
resp = self.provider.GeneralBasicOCR(req)
|
|
if resp.TextDetections:
|
|
texts = [item.DetectedText for item in resp.TextDetections]
|
|
return "".join(texts)
|
|
return ""
|
|
except Exception as e:
|
|
print(f"[OCR] 腾讯OCR API识别失败: {e}")
|
|
return ""
|
|
|
|
|
|
def get_ocr_provider(ocr_type: Optional[str] = None) -> OCRProvider:
|
|
"""
|
|
获取OCR提供者
|
|
|
|
Args:
|
|
ocr_type: OCR类型 ('paddleocr', 'easyocr', 'baidu', 'tencent')
|
|
如果为None,则从环境变量或config.json读取
|
|
|
|
Returns:
|
|
OCRProvider实例
|
|
"""
|
|
if ocr_type is None:
|
|
# 优先从环境变量读取
|
|
ocr_type = os.environ.get("OCR_TYPE", "").lower()
|
|
|
|
# 如果环境变量未设置,尝试从config.json读取
|
|
if not ocr_type:
|
|
try:
|
|
config_path = os.path.join(os.path.dirname(__file__), "config.json")
|
|
if os.path.exists(config_path):
|
|
with open(config_path, 'r', encoding='utf-8') as f:
|
|
config = json.load(f)
|
|
ocr_type = config.get("ocr_type", "").lower()
|
|
except Exception:
|
|
pass
|
|
|
|
# 默认使用paddleocr
|
|
if not ocr_type:
|
|
ocr_type = "paddleocr"
|
|
|
|
ocr_type = ocr_type.lower()
|
|
|
|
if ocr_type == "easyocr":
|
|
return EasyOCRProvider()
|
|
elif ocr_type == "baidu":
|
|
return BaiduOCRProvider()
|
|
elif ocr_type == "tencent":
|
|
return TencentOCRProvider()
|
|
else:
|
|
return PaddleOCRProvider()
|
|
|
|
|
|
# 全局OCR提供者实例(单例模式)
|
|
_global_ocr_provider: Optional[OCRProvider] = None
|
|
|
|
|
|
def get_global_ocr_provider() -> OCRProvider:
|
|
"""获取全局OCR提供者实例(单例)"""
|
|
global _global_ocr_provider
|
|
if _global_ocr_provider is None:
|
|
_global_ocr_provider = get_ocr_provider()
|
|
_global_ocr_provider.initialize()
|
|
return _global_ocr_provider
|
|
|
|
|
|
def recognize_image(image_path: str, ocr_type: Optional[str] = None) -> str:
|
|
"""
|
|
识别图片中的文字(便捷函数)
|
|
|
|
Args:
|
|
image_path: 图片路径
|
|
ocr_type: OCR类型(可选)
|
|
|
|
Returns:
|
|
识别到的文字
|
|
"""
|
|
try:
|
|
img = Image.open(image_path)
|
|
provider = get_global_ocr_provider() if ocr_type is None else get_ocr_provider(ocr_type)
|
|
if not provider.initialized:
|
|
provider.initialize()
|
|
return provider.recognize(img)
|
|
except Exception as e:
|
|
print(f"[OCR] 识别失败: {e}")
|
|
return ""
|
|
|
|
|
|
if __name__ == "__main__":
|
|
# 测试代码
|
|
import sys
|
|
if len(sys.argv) > 1:
|
|
image_path = sys.argv[1]
|
|
ocr_type = sys.argv[2] if len(sys.argv) > 2 else None
|
|
|
|
start = time.time()
|
|
text = recognize_image(image_path, ocr_type)
|
|
elapsed = (time.time() - start) * 1000
|
|
|
|
print(f"识别结果: {text}")
|
|
print(f"耗时: {elapsed:.0f}ms")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|