refactor: Remove outdated files and enhance Web GUI functionality
- 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.
This commit is contained in:
1 parent
b0bd7c72c8
commit
836a31d817
59 files changed
+17232
-6965
No files matched your search
+321
-88
@@ -1,6 +1,7 @@
|
||||
import subprocess
|
||||
from datetime import datetime, timedelta
|
||||
import os
|
||||
import warnings
|
||||
|
||||
# PaddleOCR 3.x 会在初始化/导入时进行模型源连通性检查;在国内网络环境下容易卡住。
|
||||
# 这里提前设置环境变量,避免启动耗时/卡死。
|
||||
@@ -8,6 +9,11 @@ os.environ.setdefault("DISABLE_MODEL_SOURCE_CHECK", "True")
|
||||
# 额外抑制 paddle/oneDNN/glog 的冗余信息(INFO/WARNING)
|
||||
os.environ.setdefault("GLOG_minloglevel", "2")
|
||||
os.environ.setdefault("OMP_NUM_THREADS", "1")
|
||||
|
||||
# 抑制 PyTorch DataLoader 的 pin_memory 警告(当没有 GPU 时,EasyOCR 会触发此警告)
|
||||
warnings.filterwarnings("ignore", message=".*pin_memory.*", category=UserWarning)
|
||||
warnings.filterwarnings("ignore", message=".*accelerator.*", category=UserWarning)
|
||||
|
||||
import time
|
||||
from PIL import Image, ImageFilter
|
||||
import numpy as np
|
||||
@@ -22,6 +28,9 @@ import base64
|
||||
from typing import Tuple, Optional
|
||||
import time as time_module
|
||||
|
||||
# 外部完整版 fudai 逻辑所在的工作树路径,用于镜像 screenshot 给那边使用
|
||||
_EXTERNAL_AXF_SCREENSHOT = r"C:\Users\12742\.cursor\worktrees\douyin_guaji-main\axf\pic\screenshot.png"
|
||||
|
||||
def _safe_replace_file(tmp_file: str, out_file: str, max_retries: int = 5) -> bool:
|
||||
"""安全地替换文件,处理Windows文件锁定问题。
|
||||
|
||||
@@ -140,37 +149,85 @@ def _safe_replace_file(tmp_file: str, out_file: str, max_retries: int = 5) -> bo
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def _mirror_screenshot_to_external(src_file: str) -> None:
|
||||
"""将当前项目下的 screenshot.png 同步一份到外部 axf 目录,便于完整版代码复用。
|
||||
|
||||
若外部目录/路径不存在或复制失败,会静默忽略,不影响主流程。
|
||||
"""
|
||||
try:
|
||||
external_path = _EXTERNAL_AXF_SCREENSHOT
|
||||
if not external_path:
|
||||
return
|
||||
external_dir = os.path.dirname(external_path)
|
||||
if not external_dir:
|
||||
return
|
||||
os.makedirs(external_dir, exist_ok=True)
|
||||
if not os.path.exists(src_file):
|
||||
return
|
||||
tmp = external_path + ".tmp"
|
||||
import shutil
|
||||
|
||||
shutil.copyfile(src_file, tmp)
|
||||
_safe_replace_file(tmp, external_path)
|
||||
except Exception:
|
||||
# 任何错误都不应该影响截图主流程
|
||||
pass
|
||||
|
||||
class underlying_operations:
|
||||
"""底层操作类"""
|
||||
def __init__(self):
|
||||
# 关闭文档方向/矫正等重型前处理:我们的截图是手机UI,不是扫描文档。
|
||||
# 支持延迟初始化(测试流程/只做点击时不需要 OCR)。
|
||||
self.ocr = None
|
||||
self.ocr_type = None # 'easyocr' 或 'paddleocr'
|
||||
if not str(os.environ.get("SKIP_OCR_INIT", "")).strip():
|
||||
# 在导入和实例化 PaddleOCR 时重定向 stdout/stderr,
|
||||
# 以抑制其在控制台打印的“Checking connectivity/create model”等信息。
|
||||
# 优先使用EasyOCR(更快),如果失败则回退到PaddleOCR
|
||||
# 首先尝试EasyOCR
|
||||
try:
|
||||
devnull = open(os.devnull, "w")
|
||||
with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(devnull):
|
||||
from paddleocr import PaddleOCR
|
||||
self.ocr = PaddleOCR(
|
||||
lang="ch",
|
||||
ocr_version="PP-OCRv4",
|
||||
use_doc_orientation_classify=False,
|
||||
use_doc_unwarping=False,
|
||||
use_textline_orientation=False,
|
||||
)
|
||||
import easyocr
|
||||
# 只加载中文和英文,加快初始化速度
|
||||
self.ocr = easyocr.Reader(['ch_sim', 'en'], gpu=False, verbose=False)
|
||||
self.ocr_type = 'easyocr'
|
||||
print("[OCR] 使用 EasyOCR(快速模式)")
|
||||
try:
|
||||
devnull.close()
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
# 若静默初始化失败,保留 None 并允许后续按需初始化,避免阻塞启动。
|
||||
except Exception as e:
|
||||
# EasyOCR初始化失败,回退到PaddleOCR
|
||||
try:
|
||||
devnull.close()
|
||||
except Exception:
|
||||
pass
|
||||
self.ocr = None
|
||||
try:
|
||||
devnull = open(os.devnull, "w")
|
||||
with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(devnull):
|
||||
from paddleocr import PaddleOCR
|
||||
self.ocr = PaddleOCR(
|
||||
lang="ch",
|
||||
ocr_version="PP-OCRv4",
|
||||
use_doc_orientation_classify=False,
|
||||
use_doc_unwarping=False,
|
||||
use_textline_orientation=False,
|
||||
)
|
||||
self.ocr_type = 'paddleocr'
|
||||
print("[OCR] EasyOCR不可用,使用 PaddleOCR(备选方案)")
|
||||
print(f"[OCR] 提示:安装EasyOCR可提升速度,运行: pip install easyocr")
|
||||
try:
|
||||
devnull.close()
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
# 若静默初始化失败,保留 None 并允许后续按需初始化,避免阻塞启动。
|
||||
try:
|
||||
devnull.close()
|
||||
except Exception:
|
||||
pass
|
||||
self.ocr = None
|
||||
self.ocr_type = None
|
||||
logging.disable(logging.DEBUG)
|
||||
logging.disable(logging.WARNING)
|
||||
|
||||
@@ -193,27 +250,48 @@ class underlying_operations:
|
||||
def _ensure_ocr(self):
|
||||
if self.ocr is not None:
|
||||
return
|
||||
# 优先尝试EasyOCR
|
||||
try:
|
||||
devnull = open(os.devnull, "w")
|
||||
with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(devnull):
|
||||
from paddleocr import PaddleOCR
|
||||
self.ocr = PaddleOCR(
|
||||
lang="ch",
|
||||
ocr_version="PP-OCRv4",
|
||||
use_doc_orientation_classify=False,
|
||||
use_doc_unwarping=False,
|
||||
use_textline_orientation=False,
|
||||
)
|
||||
import easyocr
|
||||
self.ocr = easyocr.Reader(['ch_sim', 'en'], gpu=False, verbose=False)
|
||||
self.ocr_type = 'easyocr'
|
||||
print("[OCR] 延迟初始化:使用 EasyOCR(快速模式)")
|
||||
try:
|
||||
devnull.close()
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
# EasyOCR失败,回退到PaddleOCR
|
||||
try:
|
||||
devnull.close()
|
||||
except Exception:
|
||||
pass
|
||||
self.ocr = None
|
||||
try:
|
||||
devnull = open(os.devnull, "w")
|
||||
with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(devnull):
|
||||
from paddleocr import PaddleOCR
|
||||
self.ocr = PaddleOCR(
|
||||
lang="ch",
|
||||
ocr_version="PP-OCRv4",
|
||||
use_doc_orientation_classify=False,
|
||||
use_doc_unwarping=False,
|
||||
use_textline_orientation=False,
|
||||
)
|
||||
self.ocr_type = 'paddleocr'
|
||||
print("[OCR] 延迟初始化:使用 PaddleOCR(备选方案)")
|
||||
try:
|
||||
devnull.close()
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
try:
|
||||
devnull.close()
|
||||
except Exception:
|
||||
pass
|
||||
self.ocr = None
|
||||
self.ocr_type = None
|
||||
|
||||
def select_device(self):
|
||||
"""选择需要连接的设备"""
|
||||
@@ -248,6 +326,41 @@ class underlying_operations:
|
||||
num = int(num)
|
||||
return dictdevice[num]
|
||||
|
||||
def _find_pic_path(self, picname: str, for_reading: bool = True) -> Optional[str]:
|
||||
"""查找图片路径,支持新旧位置(向后兼容)
|
||||
|
||||
Args:
|
||||
picname: 图片名称(不含扩展名),如 '直播广场', '福袋内容'
|
||||
for_reading: True=读取(支持新旧位置),False=写入(使用新位置)
|
||||
|
||||
Returns:
|
||||
图片的完整路径,如果找不到且for_reading=True则返回None
|
||||
"""
|
||||
base_dir = os.path.dirname(__file__)
|
||||
pic_base = os.path.join(base_dir, 'pic')
|
||||
|
||||
# 运行时必需文件始终在根目录(不需要移动)
|
||||
runtime_files = {'screenshot', 'cut'}
|
||||
if picname in runtime_files:
|
||||
path = os.path.join(pic_base, f'{picname}.png')
|
||||
return path if (os.path.exists(path) or not for_reading) else None
|
||||
|
||||
# OCR图片文件:优先查找新位置(ocr/),然后查找旧位置(根目录)
|
||||
if for_reading:
|
||||
# 读取:先查新位置,再查旧位置(向后兼容)
|
||||
new_path = os.path.join(pic_base, 'ocr', f'{picname}.png')
|
||||
if os.path.exists(new_path):
|
||||
return new_path
|
||||
old_path = os.path.join(pic_base, f'{picname}.png')
|
||||
if os.path.exists(old_path):
|
||||
return old_path
|
||||
return None
|
||||
else:
|
||||
# 写入:使用新位置,确保目录存在
|
||||
ocr_dir = os.path.join(pic_base, 'ocr')
|
||||
os.makedirs(ocr_dir, exist_ok=True)
|
||||
return os.path.join(ocr_dir, f'{picname}.png')
|
||||
|
||||
def get_screenshot(self, device_id, path='pic'):
|
||||
"""截图3个adb命令需要2S左右的时间"""
|
||||
if path == 'pic':
|
||||
@@ -294,6 +407,7 @@ class underlying_operations:
|
||||
if _valid_png(tmp_file):
|
||||
# 使用安全的文件替换函数
|
||||
if _safe_replace_file(tmp_file, out_file):
|
||||
_mirror_screenshot_to_external(out_file)
|
||||
print(f"[{timetag}] [截图] ✓ 获取屏幕截图成功")
|
||||
return True
|
||||
else:
|
||||
@@ -337,6 +451,7 @@ class underlying_operations:
|
||||
if _valid_png(tmp_file):
|
||||
# 使用安全的文件替换函数
|
||||
if _safe_replace_file(tmp_file, out_file):
|
||||
_mirror_screenshot_to_external(out_file)
|
||||
print("{} 获取屏幕截图".format(timetag))
|
||||
return True
|
||||
else:
|
||||
@@ -349,6 +464,7 @@ class underlying_operations:
|
||||
try:
|
||||
with open(tmp_file, 'rb') as src, open(out_file, 'wb') as dst:
|
||||
dst.write(src.read())
|
||||
_mirror_screenshot_to_external(out_file)
|
||||
print(f"[{timetag}] [截图] ✓ 获取屏幕截图成功(通过直接写入)")
|
||||
return True
|
||||
except (OSError, PermissionError) as e:
|
||||
@@ -365,6 +481,7 @@ class underlying_operations:
|
||||
pass
|
||||
# 尝试重命名临时文件为目标文件
|
||||
os.rename(tmp_file, out_file)
|
||||
_mirror_screenshot_to_external(out_file)
|
||||
print("{} 获取屏幕截图(通过重命名临时文件)".format(timetag))
|
||||
return True
|
||||
except Exception:
|
||||
@@ -410,36 +527,7 @@ class underlying_operations:
|
||||
os.system("%s -s %s shell input keyevent 4" % (self._adb(), device_id))
|
||||
print("点击返回键")
|
||||
|
||||
def get_battery_level(self, device_id):
|
||||
"""获取设备电量信息"""
|
||||
battery_info = subprocess.Popen("%s -s %s shell dumpsys battery" % (self._adb(), device_id), shell=True,
|
||||
stdout=subprocess.PIPE)
|
||||
battery_info_string = battery_info.stdout.read()
|
||||
battery_info_string = bytes.decode(battery_info_string)
|
||||
location = re.search('level:', battery_info_string)
|
||||
if not location:
|
||||
print("[警告] 无法解析电量信息,返回默认值100")
|
||||
return 100
|
||||
span = location.span()
|
||||
start, end = span
|
||||
start = end + 1
|
||||
# 防止越界
|
||||
max_end = min(len(battery_info_string), start + 10)
|
||||
for i in range(max_end - start):
|
||||
end = start + i
|
||||
if end >= len(battery_info_string) or battery_info_string[end] == "\n":
|
||||
break
|
||||
if end <= start:
|
||||
print("[警告] 无法解析电量信息,返回默认值100")
|
||||
return 100
|
||||
battery_level_str = battery_info_string[start:end].strip()
|
||||
try:
|
||||
battery_level = int(battery_level_str)
|
||||
print("设备当前电量为{}".format(battery_level))
|
||||
return battery_level
|
||||
except ValueError:
|
||||
print(f"[警告] 电量解析失败:'{battery_level_str}',返回默认值100")
|
||||
return 100
|
||||
# 电量检测方法已删除
|
||||
|
||||
def get_device_resolution(self, device_id):
|
||||
"""获取设备分辨率"""
|
||||
@@ -505,25 +593,139 @@ class underlying_operations:
|
||||
print("保存中奖截图失败")
|
||||
|
||||
def cut_pic(self, left_up=(0, 63), right_down=(1080, 1620), target='', name=''):
|
||||
'''裁剪图片,获取需要的区域小图片方便识别'''
|
||||
if target == '' or target == False:
|
||||
path = os.path.dirname(__file__) + '/pic'
|
||||
pic1_path = path + '/screenshot.png'
|
||||
pic = Image.open(pic1_path)
|
||||
if name == '':
|
||||
cut_pic_path = path + '/cut.png'
|
||||
else:
|
||||
cut_pic_path = path + '/' + name + '.png'
|
||||
pic.crop((left_up[0], left_up[1], right_down[0], right_down[1])).save(cut_pic_path)
|
||||
return True
|
||||
path_target = os.path.dirname(__file__) + '/pic/' + target
|
||||
pic1_path = path_target + '/screenshot.png'
|
||||
pic = Image.open(pic1_path)
|
||||
if name == '':
|
||||
cut_pic_path = path_target + '/cut.png'
|
||||
else:
|
||||
cut_pic_path = path_target + '/' + name + '.png'
|
||||
pic.crop((left_up[0], left_up[1], right_down[0], right_down[1])).save(cut_pic_path)
|
||||
'''裁剪图片,获取需要的区域小图片方便识别
|
||||
|
||||
添加了错误处理:
|
||||
- 检查文件是否存在
|
||||
- 验证图片完整性
|
||||
- 重试机制(如果文件损坏)
|
||||
- 异常处理避免程序崩溃
|
||||
'''
|
||||
max_retries = 3
|
||||
retry_delay = 0.1
|
||||
|
||||
for attempt in range(max_retries):
|
||||
try:
|
||||
if target == '' or target == False:
|
||||
path = os.path.dirname(__file__) + '/pic'
|
||||
pic1_path = path + '/screenshot.png'
|
||||
|
||||
# 检查文件是否存在
|
||||
if not os.path.exists(pic1_path):
|
||||
if attempt < max_retries - 1:
|
||||
time_module.sleep(retry_delay * (attempt + 1))
|
||||
continue
|
||||
raise FileNotFoundError(f"截图文件不存在: {pic1_path}")
|
||||
|
||||
# 验证文件大小(至少应该有一些内容)
|
||||
if os.path.getsize(pic1_path) < 100:
|
||||
if attempt < max_retries - 1:
|
||||
time_module.sleep(retry_delay * (attempt + 1))
|
||||
continue
|
||||
raise ValueError(f"截图文件太小,可能损坏: {pic1_path}")
|
||||
|
||||
# 尝试打开并验证图片
|
||||
try:
|
||||
pic = Image.open(pic1_path)
|
||||
# 验证图片完整性(通过访问尺寸属性)
|
||||
_ = pic.size
|
||||
# 确保图片已加载
|
||||
pic.load()
|
||||
except (SyntaxError, IOError, OSError) as e:
|
||||
# 图片损坏,重试或返回False
|
||||
if attempt < max_retries - 1:
|
||||
print(f"[警告] 图片文件可能损坏,重试中 ({attempt + 1}/{max_retries}): {e}")
|
||||
time_module.sleep(retry_delay * (attempt + 1))
|
||||
continue
|
||||
# 最后一次尝试失败,让外层异常处理
|
||||
raise
|
||||
|
||||
if name == '':
|
||||
cut_pic_path = path + '/cut.png'
|
||||
else:
|
||||
# 使用新的路径查找方法(写入到新位置ocr/)
|
||||
cut_pic_path = self._find_pic_path(name, for_reading=False)
|
||||
|
||||
# 验证裁剪坐标有效性
|
||||
width, height = pic.size
|
||||
left, top = left_up
|
||||
right, bottom = right_down
|
||||
if left < 0 or top < 0 or right > width or bottom > height or left >= right or top >= bottom:
|
||||
raise ValueError(f"裁剪坐标无效: left_up={left_up}, right_down={right_down}, image_size={pic.size}")
|
||||
|
||||
pic.crop((left, top, right, bottom)).save(cut_pic_path)
|
||||
return True
|
||||
|
||||
else:
|
||||
path_target = os.path.dirname(__file__) + '/pic/' + target
|
||||
pic1_path = path_target + '/screenshot.png'
|
||||
|
||||
# 检查文件是否存在
|
||||
if not os.path.exists(pic1_path):
|
||||
if attempt < max_retries - 1:
|
||||
time_module.sleep(retry_delay * (attempt + 1))
|
||||
continue
|
||||
raise FileNotFoundError(f"截图文件不存在: {pic1_path}")
|
||||
|
||||
# 验证文件大小
|
||||
if os.path.getsize(pic1_path) < 100:
|
||||
if attempt < max_retries - 1:
|
||||
time_module.sleep(retry_delay * (attempt + 1))
|
||||
continue
|
||||
raise ValueError(f"截图文件太小,可能损坏: {pic1_path}")
|
||||
|
||||
# 尝试打开并验证图片
|
||||
try:
|
||||
pic = Image.open(pic1_path)
|
||||
_ = pic.size
|
||||
pic.load()
|
||||
except (SyntaxError, IOError, OSError) as e:
|
||||
# 图片损坏,重试或返回False
|
||||
if attempt < max_retries - 1:
|
||||
print(f"[警告] 图片文件可能损坏,重试中 ({attempt + 1}/{max_retries}): {e}")
|
||||
time_module.sleep(retry_delay * (attempt + 1))
|
||||
continue
|
||||
# 最后一次尝试失败,让外层异常处理
|
||||
raise
|
||||
|
||||
if name == '':
|
||||
cut_pic_path = path_target + '/cut.png'
|
||||
else:
|
||||
cut_pic_path = path_target + '/' + name + '.png'
|
||||
|
||||
# 验证裁剪坐标有效性
|
||||
width, height = pic.size
|
||||
left, top = left_up
|
||||
right, bottom = right_down
|
||||
if left < 0 or top < 0 or right > width or bottom > height or left >= right or top >= bottom:
|
||||
error_msg = f"裁剪坐标无效: left_up={left_up}, right_down={right_down}, image_size={pic.size}"
|
||||
if attempt == max_retries - 1:
|
||||
print(f"[错误] {error_msg}")
|
||||
return False
|
||||
continue
|
||||
|
||||
pic.crop((left, top, right, bottom)).save(cut_pic_path)
|
||||
return True
|
||||
|
||||
except (SyntaxError, IOError, OSError, FileNotFoundError, ValueError) as e:
|
||||
# 最后一次尝试失败,打印错误信息
|
||||
if attempt == max_retries - 1:
|
||||
error_msg = f"[错误] 裁剪图片失败 (尝试 {max_retries} 次): {e}"
|
||||
print(error_msg)
|
||||
print(f" 源文件: {pic1_path}")
|
||||
print(f" 目标文件: {cut_pic_path if 'cut_pic_path' in locals() else 'N/A'}")
|
||||
# 不抛出异常,返回 False 让调用者处理
|
||||
return False
|
||||
# 继续重试
|
||||
continue
|
||||
except Exception as e:
|
||||
# 其他未知异常
|
||||
if attempt == max_retries - 1:
|
||||
print(f"[错误] 裁剪图片时发生未知错误: {e}")
|
||||
return False
|
||||
continue
|
||||
|
||||
return False
|
||||
|
||||
def analyse_pic_word(self, picname='', change_color=0):
|
||||
"""识别图像中的文字, change_color=1或2为不同的二值化模式,其他不做处理
|
||||
@@ -536,11 +738,15 @@ class underlying_operations:
|
||||
if self.ocr is None:
|
||||
return ''
|
||||
|
||||
path = os.path.dirname(__file__) + '/pic'
|
||||
if picname == '':
|
||||
# cut.png 始终在根目录
|
||||
path = os.path.dirname(__file__) + '/pic'
|
||||
pic_path = path + '/cut.png'
|
||||
else:
|
||||
pic_path = path + '/' + picname + '.png'
|
||||
# 使用新的路径查找方法(支持新旧位置)
|
||||
pic_path = self._find_pic_path(picname, for_reading=True)
|
||||
if not pic_path:
|
||||
return ''
|
||||
|
||||
# 检查文件是否存在
|
||||
if not os.path.exists(pic_path):
|
||||
@@ -568,9 +774,10 @@ class underlying_operations:
|
||||
# 性能优化:先用原尺寸跑一次 OCR;只有识别为空时才放大重试。
|
||||
w, h = img.size
|
||||
# 优化:对于很小的图片,直接放大,避免浪费一次OCR调用
|
||||
if max(w, h) < 100:
|
||||
# 提高阈值:对于UI文字(如"直播广场"),即使是172x58这样稍大的尺寸也需要放大
|
||||
if max(w, h) < 200:
|
||||
try:
|
||||
scale = max(2, 200 // max(w, h, 1)) # 至少放大到200像素
|
||||
scale = max(2, 300 // max(w, h, 1)) # 至少放大到300像素,提高小文字识别率
|
||||
img = img.resize((w * scale, h * scale), Image.BICUBIC)
|
||||
w, h = img.size
|
||||
except Exception:
|
||||
@@ -584,17 +791,28 @@ class underlying_operations:
|
||||
img_sharpened = img.filter(ImageFilter.UnsharpMask(radius=1, percent=150, threshold=3))
|
||||
# 再增强对比度(轻微增强,避免过度处理)
|
||||
enhancer = ImageEnhance.Contrast(img_sharpened)
|
||||
img_enhanced = enhancer.enhance(1.15) # 增强15%对比度
|
||||
# 根据图片尺寸动态调整对比度:小图片需要更强的对比度
|
||||
contrast_factor = 1.25 if max(w, h) < 300 else 1.15 # 小图片增强25%对比度
|
||||
img_enhanced = enhancer.enhance(contrast_factor)
|
||||
img1 = img_enhanced
|
||||
except Exception:
|
||||
# 如果增强失败,回退到原来的锐化
|
||||
img1 = img.filter(ImageFilter.SHARPEN)
|
||||
|
||||
img_np = np.array(img1)
|
||||
result = self.ocr.ocr(img_np)
|
||||
if result == [None]:
|
||||
return ''
|
||||
text = self.extract_ocr_content(result)
|
||||
|
||||
# 根据OCR类型调用不同的识别方法
|
||||
# 如果没有设置ocr_type,默认使用PaddleOCR格式(向后兼容)
|
||||
if getattr(self, 'ocr_type', None) == 'easyocr':
|
||||
# EasyOCR: readtext返回格式为 [(bbox, text, confidence), ...]
|
||||
result = self.ocr.readtext(img_np)
|
||||
text = self.extract_ocr_content(result)
|
||||
else:
|
||||
# PaddleOCR: ocr返回格式为 [[...]] 或 [...]
|
||||
result = self.ocr.ocr(img_np)
|
||||
if result == [None]:
|
||||
return ''
|
||||
text = self.extract_ocr_content(result)
|
||||
|
||||
# 如果识别为空且图片较小,尝试放大重试(精度优化:使用更好的放大算法和增强处理)
|
||||
if (not text) and max(w, h) <= 1200:
|
||||
@@ -610,15 +828,25 @@ class underlying_operations:
|
||||
img2 = img2_enhanced
|
||||
except Exception:
|
||||
img2 = img2.filter(ImageFilter.SHARPEN)
|
||||
result2 = self.ocr.ocr(np.array(img2))
|
||||
if result2 != [None]:
|
||||
text = self.extract_ocr_content(result2)
|
||||
result = result2
|
||||
|
||||
if getattr(self, 'ocr_type', None) == 'easyocr':
|
||||
result2 = self.ocr.readtext(np.array(img2))
|
||||
text2 = self.extract_ocr_content(result2)
|
||||
if text2:
|
||||
text = text2
|
||||
result = result2
|
||||
else:
|
||||
result2 = self.ocr.ocr(np.array(img2))
|
||||
if result2 != [None]:
|
||||
text2 = self.extract_ocr_content(result2)
|
||||
if text2:
|
||||
text = text2
|
||||
result = result2
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 对关键字段做轻量级调试输出:图片很清楚但识别为空时,通常是返回结构变化或未检出文本
|
||||
if picname in ("fudai_content", "fudai_countdown") and not text:
|
||||
if picname in ("福袋内容", "福袋倒计时") and not text:
|
||||
try:
|
||||
if isinstance(result, list) and result and isinstance(result[0], dict):
|
||||
print(f"OCR调试({picname}): result[0] keys={list(result[0].keys())}")
|
||||
@@ -634,8 +862,13 @@ class underlying_operations:
|
||||
ocr_result = content
|
||||
|
||||
def _extract_text_from_item(item):
|
||||
# 兼容旧格式:[box, (text, score)]
|
||||
# 兼容EasyOCR格式:[(bbox, text, confidence), ...] -> (bbox, text, confidence)
|
||||
if isinstance(item, (list, tuple)) and len(item) >= 2:
|
||||
# EasyOCR格式:item = (bbox, text, confidence),text在索引1
|
||||
if isinstance(item[1], str):
|
||||
return item[1]
|
||||
|
||||
# 兼容旧格式:[box, (text, score)]
|
||||
second = item[1]
|
||||
if isinstance(second, (list, tuple)) and len(second) >= 1:
|
||||
if isinstance(second[0], str):
|
||||
@@ -685,9 +918,10 @@ class underlying_operations:
|
||||
def _extract_xy_from_item(item):
|
||||
"""尽力从 OCR item 中提取用于排序的 (y, x)。无法提取则返回 None。"""
|
||||
try:
|
||||
# 旧格式:item = [box, (text, score)],box 为 4 点坐标
|
||||
if isinstance(item, (list, tuple)) and len(item) >= 1:
|
||||
box = item[0]
|
||||
# EasyOCR格式:bbox = [[x1,y1], [x2,y2], [x3,y3], [x4,y4]]
|
||||
# PaddleOCR格式:box 为 4 点坐标列表
|
||||
if isinstance(box, (list, tuple)) and box:
|
||||
xs = []
|
||||
ys = []
|
||||
@@ -1371,4 +1605,3 @@ class underlying_operations:
|
||||
return False
|
||||
time.sleep(0.2)
|
||||
|
||||
|
||||
Reference in new issue
Block a user