拆分 underlying_operations (3021 → 5 子模块 + 2582 行原文件)
把 douyin/core/underlying_operations.py 中 6 个零 self 引用的方法搬到
douyin/core/underlying_operations_pkg/ 子包,类内方法变成 1 行 forwarding。
原文件保留 underlying_operations 巨型类(>50 个实例方法用 self)。
新建子包:
- adb_helpers (34) _adb_path / _pick_adbkeyboard_ime
- pic_path (65) _find_pic_path 按名称查找图片路径
- ocr_content (228) extract_ocr_content OCR 文本拼接 + 置信度
- countdown (179) check_countdown 倒计时文本解析(含 OCR 字符纠错)
- bounds (17) _parse_bounds 解析 UI dump 的 [x1,y1][x2,y2]
策略:6 个方法的 self 引用全为 0,纯算法逻辑直接搬到 module-level;
类内对应方法保留装饰器和签名,body 改为 1 行 forwarding 调用:
@staticmethod
def _adb_path() -> str:
return _impl_adb_path()
外部调用全部不需修改:
- ``self._find_pic_path(...)`` 实例方法 forwarding 仍工作
- ``cls._adb_path()`` staticmethod forwarding 仍工作
- ``ReservationHandler._parse_bounds(...)`` 外部 5 处引用零修改
修复发现:
- countdown.py 原本 ``import datetime``(应为 ``from datetime import datetime,
timedelta``),导致 datetime.now()/timedelta() 触发 NameError 后被外层
except 吞掉返回 False。修正后 check_countdown('5:30') 正确返回 (330, <ts>)
- 子模块内部用 _uo_log,加本地实现避免对原文件的循环依赖
回归:
- 6 个新文件 + 改写后 underlying_operations.py compileall 通过
- pytest 353 passed / 1 skipped
- check_countdown / extract_ocr_content / _parse_bounds /
_pick_adbkeyboard_ime / _find_pic_path / _adb_path 6 个 forwarding 全部正确
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
1 parent
246c80498e
commit
254820e6dc
7 files changed
+592
-459
No files matched your search
@@ -75,6 +75,16 @@ def _uo_log(msg: str, level: str = "INFO") -> None:
|
||||
pass
|
||||
|
||||
|
||||
|
||||
# 已搬到子包 douyin.core.underlying_operations_pkg 的 6 个方法实现
|
||||
from douyin.core.underlying_operations_pkg import (
|
||||
_adb_path as _impl_adb_path,
|
||||
_find_pic_path as _impl_find_pic_path,
|
||||
_parse_bounds as _impl_parse_bounds,
|
||||
_pick_adbkeyboard_ime as _impl_pick_adbkeyboard_ime,
|
||||
check_countdown as _impl_check_countdown,
|
||||
extract_ocr_content as _impl_extract_ocr_content,
|
||||
)
|
||||
class underlying_operations:
|
||||
"""底层操作类"""
|
||||
|
||||
@@ -143,12 +153,7 @@ class underlying_operations:
|
||||
|
||||
@staticmethod
|
||||
def _adb_path() -> str:
|
||||
"""返回可用于 subprocess(list_args) 的 adb 路径(不带外层引号)。"""
|
||||
adb = str(os.environ.get("ADB_EXECUTABLE", "adb") or "adb")
|
||||
if adb.startswith('"') and adb.endswith('"'):
|
||||
adb = adb[1:-1]
|
||||
return adb
|
||||
|
||||
return _impl_adb_path()
|
||||
def _adb_args(self, device_id: str, *args: object) -> list[str]:
|
||||
return [self._adb_path(), "-s", str(device_id), *[str(arg) for arg in args]]
|
||||
|
||||
@@ -249,60 +254,8 @@ 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
|
||||
"""
|
||||
try:
|
||||
from douyin.core import path_config
|
||||
|
||||
pic_base = path_config.get_pic_dir()
|
||||
except Exception:
|
||||
from douyin.core import path_config
|
||||
|
||||
pic_base = path_config.get_pic_dir()
|
||||
|
||||
# 运行时必需文件始终在根目录(不需要移动)
|
||||
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图片文件:按分类组织到子目录
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
category = douyin_screenshot_manager.get_category_for_picname(picname)
|
||||
except Exception:
|
||||
category = "others"
|
||||
|
||||
if for_reading:
|
||||
# 读取:先查分类目录,再查旧位置(向后兼容)
|
||||
# 1. 新位置(分类目录)
|
||||
category_path = os.path.join(pic_base, "ocr", category, f"{picname}.png")
|
||||
if os.path.exists(category_path):
|
||||
return category_path
|
||||
# 2. 旧位置(ocr根目录)
|
||||
old_ocr_path = os.path.join(pic_base, "ocr", f"{picname}.png")
|
||||
if os.path.exists(old_ocr_path):
|
||||
return old_ocr_path
|
||||
# 3. 更旧的位置(pic根目录)
|
||||
old_root_path = os.path.join(pic_base, f"{picname}.png")
|
||||
if os.path.exists(old_root_path):
|
||||
return old_root_path
|
||||
return None
|
||||
else:
|
||||
# 写入:使用分类目录,确保目录存在
|
||||
category_dir = os.path.join(pic_base, "ocr", category)
|
||||
os.makedirs(category_dir, exist_ok=True)
|
||||
return os.path.join(category_dir, f"{picname}.png")
|
||||
|
||||
def _find_pic_path(self, picname: str, for_reading: bool = True):
|
||||
return _impl_find_pic_path(picname, for_reading)
|
||||
def get_screenshot(self, device_id, path="pic", use_service: bool = False):
|
||||
"""截图(支持后台服务模式)
|
||||
|
||||
@@ -1768,224 +1721,8 @@ class underlying_operations:
|
||||
|
||||
return digits
|
||||
|
||||
def extract_ocr_content(self, content=None, return_confidence=False):
|
||||
"""对OCR识别到的内容进行取值和拼接,变成完整的一段内容
|
||||
|
||||
参数:
|
||||
content: OCR识别结果
|
||||
return_confidence: 是否返回置信度信息(默认False,保持向后兼容)
|
||||
|
||||
返回:
|
||||
如果return_confidence=False: 返回文本字符串
|
||||
如果return_confidence=True: 返回(text, confidence_info)元组,其中confidence_info是置信度信息字典
|
||||
"""
|
||||
ocr_result = content or []
|
||||
|
||||
# 用于收集置信度信息
|
||||
confidence_scores = []
|
||||
confidence_info = {
|
||||
"avg_confidence": 0.0,
|
||||
"min_confidence": 1.0,
|
||||
"max_confidence": 0.0,
|
||||
"item_count": 0,
|
||||
}
|
||||
|
||||
def _extract_text_and_confidence_from_item(item):
|
||||
"""提取文本和置信度"""
|
||||
text = ""
|
||||
confidence = None
|
||||
|
||||
# 兼容EasyOCR格式:[(bbox, text, confidence), ...] -> (bbox, text, confidence)
|
||||
if isinstance(item, (list, tuple)) and len(item) >= 2:
|
||||
# EasyOCR格式:item = (bbox, text, confidence),text在索引1,confidence在索引2
|
||||
if len(item) >= 3:
|
||||
confidence = item[2]
|
||||
if isinstance(item[1], str):
|
||||
text = item[1]
|
||||
return text, confidence
|
||||
|
||||
# 兼容旧格式:[box, (text, score)]
|
||||
second = item[1]
|
||||
if isinstance(second, (list, tuple)) and len(second) >= 1:
|
||||
if isinstance(second[0], str):
|
||||
return second[0]
|
||||
if isinstance(second, dict):
|
||||
for key in ("text", "rec_text", "transcription"):
|
||||
val = second.get(key)
|
||||
if isinstance(val, str) and val:
|
||||
return val
|
||||
if isinstance(second, str):
|
||||
return second
|
||||
|
||||
# 兼容新格式:dict / 对象
|
||||
if isinstance(item, dict):
|
||||
# 常见:rec_texts 为字符串列表
|
||||
for list_key in ("rec_texts", "texts", "text_list"):
|
||||
vals = item.get(list_key)
|
||||
if isinstance(vals, list) and vals:
|
||||
vals = [v for v in vals if isinstance(v, str) and v]
|
||||
if vals:
|
||||
return "".join(vals)
|
||||
for key in ("text", "rec_text", "transcription"):
|
||||
val = item.get(key)
|
||||
if isinstance(val, str) and val:
|
||||
return val
|
||||
|
||||
for attr in ("text", "rec_text", "transcription"):
|
||||
val = getattr(item, attr, None)
|
||||
if isinstance(val, str) and val:
|
||||
return val
|
||||
|
||||
# 对象属性里也可能是列表
|
||||
for list_attr in ("rec_texts", "texts", "text_list"):
|
||||
vals = getattr(item, list_attr, None)
|
||||
if isinstance(vals, list) and vals:
|
||||
vals = [v for v in vals if isinstance(v, str) and v]
|
||||
if vals:
|
||||
return "".join(vals)
|
||||
|
||||
return ""
|
||||
|
||||
# PaddleOCR 可能返回 [[...]] 或 [...]
|
||||
items = ocr_result
|
||||
if (
|
||||
isinstance(ocr_result, list)
|
||||
and len(ocr_result) == 1
|
||||
and isinstance(ocr_result[0], list)
|
||||
):
|
||||
items = ocr_result[0]
|
||||
|
||||
def _extract_xy_from_item(item):
|
||||
"""尽力从 OCR item 中提取用于排序的 (y, x)。无法提取则返回 None。"""
|
||||
try:
|
||||
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 = []
|
||||
for p in box:
|
||||
if isinstance(p, (list, tuple)) and len(p) >= 2:
|
||||
xs.append(float(p[0]))
|
||||
ys.append(float(p[1]))
|
||||
if xs and ys:
|
||||
return (min(ys), min(xs))
|
||||
except Exception:
|
||||
return None
|
||||
return None
|
||||
|
||||
def _extract_text_from_item(item):
|
||||
"""提取文本(原始逻辑,保持向后兼容)"""
|
||||
# 兼容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):
|
||||
return second[0]
|
||||
if isinstance(second, dict):
|
||||
for key in ("text", "rec_text", "transcription"):
|
||||
val = second.get(key)
|
||||
if isinstance(val, str) and val:
|
||||
return val
|
||||
if isinstance(second, str):
|
||||
return second
|
||||
|
||||
# 兼容新格式:dict / 对象
|
||||
if isinstance(item, dict):
|
||||
# 常见:rec_texts 为字符串列表
|
||||
for list_key in ("rec_texts", "texts", "text_list"):
|
||||
vals = item.get(list_key)
|
||||
if isinstance(vals, list) and vals:
|
||||
vals = [v for v in vals if isinstance(v, str) and v]
|
||||
if vals:
|
||||
return "".join(vals)
|
||||
for key in ("text", "rec_text", "transcription"):
|
||||
val = item.get(key)
|
||||
if isinstance(val, str) and val:
|
||||
return val
|
||||
|
||||
for attr in ("text", "rec_text", "transcription"):
|
||||
val = getattr(item, attr, None)
|
||||
if isinstance(val, str) and val:
|
||||
return val
|
||||
|
||||
# 对象属性里也可能是列表
|
||||
for list_attr in ("rec_texts", "texts", "text_list"):
|
||||
vals = getattr(item, list_attr, None)
|
||||
if isinstance(vals, list) and vals:
|
||||
vals = [v for v in vals if isinstance(v, str) and v]
|
||||
if vals:
|
||||
return "".join(vals)
|
||||
|
||||
return ""
|
||||
|
||||
extracted_items = []
|
||||
if isinstance(items, list):
|
||||
for idx, item in enumerate(items):
|
||||
text = _extract_text_from_item(item)
|
||||
if not text:
|
||||
continue
|
||||
xy = _extract_xy_from_item(item)
|
||||
if xy is None:
|
||||
# 无坐标信息:保持原相对顺序
|
||||
extracted_items.append((1e18, float(idx), text))
|
||||
else:
|
||||
y, x = xy
|
||||
extracted_items.append((float(y), float(x), text))
|
||||
|
||||
# 按从上到下、从左到右排序;解决同一行多个框的乱序拼接(例如倒计时两段数字)
|
||||
extracted_items.sort(key=lambda t: (t[0], t[1]))
|
||||
|
||||
# 如果不需要返回置信度,直接返回文本(保持向后兼容)
|
||||
if not return_confidence:
|
||||
return "".join([t[2] for t in extracted_items])
|
||||
|
||||
# 如果需要返回置信度,提取置信度信息
|
||||
if return_confidence:
|
||||
for item in items:
|
||||
confidence = None
|
||||
# EasyOCR格式:[(bbox, text, confidence), ...]
|
||||
if isinstance(item, (list, tuple)) and len(item) >= 3:
|
||||
confidence = item[2]
|
||||
# PaddleOCR格式:[box, (text, score)]
|
||||
elif isinstance(item, (list, tuple)) and len(item) >= 2:
|
||||
second = item[1]
|
||||
if isinstance(second, (list, tuple)) and len(second) >= 2:
|
||||
confidence = second[1]
|
||||
elif isinstance(second, dict):
|
||||
confidence = second.get("confidence") or second.get("score")
|
||||
|
||||
if confidence is not None:
|
||||
try:
|
||||
conf_float = float(confidence)
|
||||
confidence_scores.append(conf_float)
|
||||
confidence_info["min_confidence"] = min(
|
||||
confidence_info["min_confidence"], conf_float
|
||||
)
|
||||
confidence_info["max_confidence"] = max(
|
||||
confidence_info["max_confidence"], conf_float
|
||||
)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
if confidence_scores:
|
||||
confidence_info["avg_confidence"] = sum(confidence_scores) / len(
|
||||
confidence_scores
|
||||
)
|
||||
confidence_info["item_count"] = len(confidence_scores)
|
||||
else:
|
||||
confidence_info["min_confidence"] = 0.0
|
||||
|
||||
return "".join([t[2] for t in extracted_items]), confidence_info
|
||||
|
||||
return "".join([t[2] for t in extracted_items])
|
||||
|
||||
def extract_ocr_content(self, content=None, return_confidence: bool = False):
|
||||
return _impl_extract_ocr_content(content, return_confidence)
|
||||
def delay(self, seconds: float = 1):
|
||||
time_module.sleep(seconds)
|
||||
|
||||
@@ -1995,167 +1732,8 @@ class underlying_operations:
|
||||
_uo_log("随机等待{}秒.".format(random_wait_seconds))
|
||||
self.delay(random_wait_seconds)
|
||||
|
||||
def check_countdown(self, last_time=""):
|
||||
"""对倒计时时间进行转化,返回 (剩余秒数, 预计开奖时间戳)。
|
||||
|
||||
兼容 OCR 常见格式与误识别:
|
||||
- 11:37 / 11:37 / 11:37后开奖
|
||||
- 1分23秒 / 23秒
|
||||
- 1137 / 934 / 31
|
||||
- 字符混淆:O->0, l/I->1, S->5 等
|
||||
"""
|
||||
|
||||
def _norm(s: str) -> str:
|
||||
t = str(s or "")
|
||||
t = re.sub(r"\s+", "", t)
|
||||
t = t.replace(":", ":")
|
||||
# 常见 OCR 混淆纠正
|
||||
trans = str.maketrans(
|
||||
{
|
||||
"O": "0",
|
||||
"o": "0",
|
||||
"Q": "0",
|
||||
"D": "0",
|
||||
"I": "1",
|
||||
"l": "1",
|
||||
"|": "1",
|
||||
"!": "1",
|
||||
"S": "5",
|
||||
"s": "5",
|
||||
"B": "8",
|
||||
"G": "6",
|
||||
"Z": "2",
|
||||
}
|
||||
)
|
||||
t = t.translate(trans)
|
||||
return t
|
||||
|
||||
def _parse_seconds(text: str) -> Optional[int]:
|
||||
t = _norm(text)
|
||||
if not t:
|
||||
return None
|
||||
|
||||
# 1) mm:ss(允许 ss 为 1 位)
|
||||
m = re.search(r"(\d{1,2})[:](\d{1,2})", t)
|
||||
if m:
|
||||
mm = int(m.group(1))
|
||||
ss = int(m.group(2))
|
||||
# 若秒数 >= 60,优先尝试交换(OCR 容易把分秒顺序颠倒)
|
||||
if ss >= 60 and mm < 60:
|
||||
mm, ss = ss, mm
|
||||
# 兜底:仍不合法则做进位
|
||||
if ss >= 60:
|
||||
mm += ss // 60
|
||||
ss = ss % 60
|
||||
return max(0, mm * 60 + ss)
|
||||
|
||||
# 2) 中文:x分y秒 / y秒
|
||||
m = re.search(r"(\d{1,2})分(\d{1,2})秒", t)
|
||||
if m:
|
||||
mm = int(m.group(1))
|
||||
ss = int(m.group(2))
|
||||
if ss >= 60:
|
||||
mm += ss // 60
|
||||
ss = ss % 60
|
||||
return max(0, mm * 60 + ss)
|
||||
m = re.search(r"(\d{1,3})秒", t)
|
||||
if m:
|
||||
return max(0, int(m.group(1)))
|
||||
|
||||
# 3) 纯数字:1137(=11:37) / 934(=9:34) / 31(=31秒)
|
||||
digits = "".join(ch for ch in t if ch.isdigit())
|
||||
if not digits:
|
||||
return None
|
||||
|
||||
if len(digits) == 4:
|
||||
a = int(digits[:2])
|
||||
b = int(digits[2:])
|
||||
# 两种解释:a:b 或 b:a。
|
||||
# 默认按“前两位=分、后两位=秒”,只有在明显异常(>15分钟)或秒不合法时才交换。
|
||||
if b < 60:
|
||||
total1 = a * 60 + b
|
||||
else:
|
||||
total1 = None
|
||||
if a < 60:
|
||||
total2 = b * 60 + a
|
||||
else:
|
||||
total2 = None
|
||||
|
||||
if total1 is not None and total1 <= 900:
|
||||
return total1
|
||||
if total2 is not None and total2 <= 900:
|
||||
return total2
|
||||
|
||||
# 若一个明显异常而另一个更合理(<=900),交换
|
||||
if total1 is not None and total2 is not None:
|
||||
if total1 > 900 and total2 <= 900:
|
||||
return total2
|
||||
if total2 > 900 and total1 <= 900:
|
||||
return total1
|
||||
|
||||
# 兜底:谁能解析就用谁;都不行则做进位
|
||||
if total1 is not None:
|
||||
return total1
|
||||
if total2 is not None:
|
||||
return total2
|
||||
|
||||
mm, ss = a, b
|
||||
mm += ss // 60
|
||||
ss = ss % 60
|
||||
return mm * 60 + ss
|
||||
|
||||
if len(digits) == 3:
|
||||
mm = int(digits[0])
|
||||
ss = int(digits[1:])
|
||||
if ss >= 60:
|
||||
# 例如 159 可能是 15:09(OCR 丢 0)
|
||||
mm2 = int(digits[:2])
|
||||
ss2 = int(digits[2])
|
||||
if ss2 < 60:
|
||||
return mm2 * 60 + ss2
|
||||
mm += ss // 60
|
||||
ss = ss % 60
|
||||
return mm * 60 + ss
|
||||
|
||||
if len(digits) == 2:
|
||||
return int(digits) # 直接当秒(更符合“临近开奖”场景)
|
||||
|
||||
if len(digits) == 1:
|
||||
return int(digits)
|
||||
|
||||
# 太长:取最后4位(OCR 常把别的数字也识别进来)
|
||||
tail = digits[-4:]
|
||||
a = int(tail[:2])
|
||||
b = int(tail[2:])
|
||||
if b >= 60 and a < 60:
|
||||
a, b = b, a
|
||||
if b >= 60:
|
||||
a += b // 60
|
||||
b = b % 60
|
||||
return a * 60 + b
|
||||
|
||||
try:
|
||||
total_seconds = _parse_seconds(last_time)
|
||||
if total_seconds is None:
|
||||
_uo_log("时间格式异常")
|
||||
return False
|
||||
_uo_log("剩余总秒数:", total_seconds)
|
||||
# 超过 15 分钟基本是误识别:按 14分50秒处理,避免卡死等待
|
||||
if total_seconds > 900:
|
||||
total_seconds = 890
|
||||
|
||||
now = datetime.now()
|
||||
_uo_log("当前时间:", now.strftime("%Y-%m-%d %H:%M:%S"))
|
||||
future_time = now + timedelta(seconds=int(total_seconds))
|
||||
future_timestamp = future_time.timestamp()
|
||||
future_datetime = datetime.fromtimestamp(future_timestamp)
|
||||
formatted_future_time = future_datetime.strftime("%Y-%m-%d %H:%M:%S")
|
||||
_uo_log("预计开奖时间:", formatted_future_time)
|
||||
return int(total_seconds), future_timestamp
|
||||
except Exception:
|
||||
_uo_log("输入的字符串不是有效的时间格式")
|
||||
return False
|
||||
|
||||
def check_countdown(self, last_time: str = "") -> tuple:
|
||||
return _impl_check_countdown(last_time)
|
||||
def swipe(
|
||||
self,
|
||||
device_id,
|
||||
@@ -2556,19 +2134,7 @@ class underlying_operations:
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def _pick_adbkeyboard_ime(imes: list[str]) -> str:
|
||||
# 兼容不同包名/组件名写法,优先匹配常见的 AdbIME
|
||||
for cand in imes or []:
|
||||
s = str(cand).strip()
|
||||
ls = s.lower()
|
||||
if "adbkeyboard" in ls and "adbime" in ls:
|
||||
return s
|
||||
for cand in imes or []:
|
||||
s = str(cand).strip()
|
||||
ls = s.lower()
|
||||
if "adbkeyboard" in ls or "adbime" in ls:
|
||||
return s
|
||||
return ""
|
||||
|
||||
return _impl_pick_adbkeyboard_ime(imes)
|
||||
def ensure_adbkeyboard_ime(
|
||||
self, device_id: str, preferred_ime: str = "com.android.adbkeyboard/.AdbIME"
|
||||
) -> Tuple[bool, str, str]:
|
||||
@@ -2865,14 +2431,9 @@ class underlying_operations:
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
@staticmethod
|
||||
def _parse_bounds(bounds: str):
|
||||
m = re.match(r"\[(\d+),(\d+)\]\[(\d+),(\d+)\]", str(bounds or ""))
|
||||
if not m:
|
||||
return None
|
||||
x1, y1, x2, y2 = map(int, m.groups())
|
||||
return x1, y1, x2, y2
|
||||
|
||||
return _impl_parse_bounds(bounds)
|
||||
def tap_by_text(
|
||||
self,
|
||||
device_id: str,
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
"""underlying_operations_pkg - underlying_operations 类的零 self 方法子包。
|
||||
|
||||
原 douyin/core/underlying_operations.py(3021 行)的 6 个零 self 方法搬出到本子包:
|
||||
|
||||
- adb_helpers _adb_path / _pick_adbkeyboard_ime
|
||||
- pic_path _find_pic_path
|
||||
- ocr_content extract_ocr_content (218 行)
|
||||
- countdown check_countdown (161 行)
|
||||
- bounds _parse_bounds
|
||||
|
||||
类 ``underlying_operations`` 留在原文件,方法保留为 1 行 @staticmethod
|
||||
forwarding(签名不变,外部调用 ``self.X()`` / ``cls.X()`` 全部兼容)。
|
||||
"""
|
||||
|
||||
from .adb_helpers import _adb_path, _pick_adbkeyboard_ime
|
||||
from .pic_path import _find_pic_path
|
||||
from .ocr_content import extract_ocr_content
|
||||
from .countdown import check_countdown
|
||||
from .bounds import _parse_bounds
|
||||
|
||||
__all__ = [
|
||||
"_adb_path",
|
||||
"_pick_adbkeyboard_ime",
|
||||
"_find_pic_path",
|
||||
"extract_ocr_content",
|
||||
"check_countdown",
|
||||
"_parse_bounds",
|
||||
]
|
||||
@@ -0,0 +1,34 @@
|
||||
"""underlying_operations_pkg.adb_helpers - ADB 辅助。
|
||||
|
||||
- _adb_path 返回可用于 subprocess(list_args) 的 adb 路径(不带外层引号)
|
||||
- _pick_adbkeyboard_ime 从 IME 列表里挑出 ADBKeyboard 的 ID
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import List
|
||||
|
||||
|
||||
def _adb_path() -> str:
|
||||
"""返回可用于 subprocess(list_args) 的 adb 路径(不带外层引号)。"""
|
||||
adb = str(os.environ.get("ADB_EXECUTABLE", "adb") or "adb")
|
||||
if adb.startswith('"') and adb.endswith('"'):
|
||||
adb = adb[1:-1]
|
||||
return adb
|
||||
|
||||
|
||||
|
||||
def _pick_adbkeyboard_ime(imes: list[str]) -> str:
|
||||
# 兼容不同包名/组件名写法,优先匹配常见的 AdbIME
|
||||
for cand in imes or []:
|
||||
s = str(cand).strip()
|
||||
ls = s.lower()
|
||||
if "adbkeyboard" in ls and "adbime" in ls:
|
||||
return s
|
||||
for cand in imes or []:
|
||||
s = str(cand).strip()
|
||||
ls = s.lower()
|
||||
if "adbkeyboard" in ls or "adbime" in ls:
|
||||
return s
|
||||
return ""
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
"""underlying_operations_pkg.bounds - bounds 字符串解析。
|
||||
|
||||
_parse_bounds: 解析 UI dump 里的 ``[x1,y1][x2,y2]`` 格式。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Optional, Tuple
|
||||
|
||||
|
||||
def _parse_bounds(bounds: str):
|
||||
m = re.match(r"\[(\d+),(\d+)\]\[(\d+),(\d+)\]", str(bounds or ""))
|
||||
if not m:
|
||||
return None
|
||||
x1, y1, x2, y2 = map(int, m.groups())
|
||||
return x1, y1, x2, y2
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
"""underlying_operations_pkg.countdown - 倒计时文本解析。
|
||||
|
||||
check_countdown: 兼容多种 OCR 误识别的倒计时格式:
|
||||
- 11:37 / 11:37 / 11:37后开奖
|
||||
- 1分23秒 / 23秒
|
||||
- 1137 / 934 / 31
|
||||
- 字符混淆纠正:O→0, l/I→1, S→5 等
|
||||
|
||||
返回 (剩余秒数, 预计开奖时间戳)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Tuple
|
||||
|
||||
# 与原 underlying_operations._uo_log 同名 logger,避免改变历史日志检索
|
||||
_LOGGER = logging.getLogger("douyin.core.underlying_operations")
|
||||
|
||||
|
||||
def _uo_log(msg, level: str = "INFO") -> None:
|
||||
"""统一底层操作日志出口;本地实现避免对原文件的循环依赖。"""
|
||||
try:
|
||||
lv = str(level or "INFO").upper()
|
||||
text = str(msg)
|
||||
if lv == "ERROR":
|
||||
_LOGGER.error(text)
|
||||
elif lv == "WARNING":
|
||||
_LOGGER.warning(text)
|
||||
elif lv == "DEBUG":
|
||||
_LOGGER.debug(text)
|
||||
else:
|
||||
_LOGGER.info(text)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def check_countdown(last_time=""):
|
||||
"""对倒计时时间进行转化,返回 (剩余秒数, 预计开奖时间戳)。
|
||||
|
||||
兼容 OCR 常见格式与误识别:
|
||||
- 11:37 / 11:37 / 11:37后开奖
|
||||
- 1分23秒 / 23秒
|
||||
- 1137 / 934 / 31
|
||||
- 字符混淆:O->0, l/I->1, S->5 等
|
||||
"""
|
||||
|
||||
def _norm(s: str) -> str:
|
||||
t = str(s or "")
|
||||
t = re.sub(r"\s+", "", t)
|
||||
t = t.replace(":", ":")
|
||||
# 常见 OCR 混淆纠正
|
||||
trans = str.maketrans(
|
||||
{
|
||||
"O": "0",
|
||||
"o": "0",
|
||||
"Q": "0",
|
||||
"D": "0",
|
||||
"I": "1",
|
||||
"l": "1",
|
||||
"|": "1",
|
||||
"!": "1",
|
||||
"S": "5",
|
||||
"s": "5",
|
||||
"B": "8",
|
||||
"G": "6",
|
||||
"Z": "2",
|
||||
}
|
||||
)
|
||||
t = t.translate(trans)
|
||||
return t
|
||||
|
||||
def _parse_seconds(text: str) -> Optional[int]:
|
||||
t = _norm(text)
|
||||
if not t:
|
||||
return None
|
||||
|
||||
# 1) mm:ss(允许 ss 为 1 位)
|
||||
m = re.search(r"(\d{1,2})[:](\d{1,2})", t)
|
||||
if m:
|
||||
mm = int(m.group(1))
|
||||
ss = int(m.group(2))
|
||||
# 若秒数 >= 60,优先尝试交换(OCR 容易把分秒顺序颠倒)
|
||||
if ss >= 60 and mm < 60:
|
||||
mm, ss = ss, mm
|
||||
# 兜底:仍不合法则做进位
|
||||
if ss >= 60:
|
||||
mm += ss // 60
|
||||
ss = ss % 60
|
||||
return max(0, mm * 60 + ss)
|
||||
|
||||
# 2) 中文:x分y秒 / y秒
|
||||
m = re.search(r"(\d{1,2})分(\d{1,2})秒", t)
|
||||
if m:
|
||||
mm = int(m.group(1))
|
||||
ss = int(m.group(2))
|
||||
if ss >= 60:
|
||||
mm += ss // 60
|
||||
ss = ss % 60
|
||||
return max(0, mm * 60 + ss)
|
||||
m = re.search(r"(\d{1,3})秒", t)
|
||||
if m:
|
||||
return max(0, int(m.group(1)))
|
||||
|
||||
# 3) 纯数字:1137(=11:37) / 934(=9:34) / 31(=31秒)
|
||||
digits = "".join(ch for ch in t if ch.isdigit())
|
||||
if not digits:
|
||||
return None
|
||||
|
||||
if len(digits) == 4:
|
||||
a = int(digits[:2])
|
||||
b = int(digits[2:])
|
||||
# 两种解释:a:b 或 b:a。
|
||||
# 默认按“前两位=分、后两位=秒”,只有在明显异常(>15分钟)或秒不合法时才交换。
|
||||
if b < 60:
|
||||
total1 = a * 60 + b
|
||||
else:
|
||||
total1 = None
|
||||
if a < 60:
|
||||
total2 = b * 60 + a
|
||||
else:
|
||||
total2 = None
|
||||
|
||||
if total1 is not None and total1 <= 900:
|
||||
return total1
|
||||
if total2 is not None and total2 <= 900:
|
||||
return total2
|
||||
|
||||
# 若一个明显异常而另一个更合理(<=900),交换
|
||||
if total1 is not None and total2 is not None:
|
||||
if total1 > 900 and total2 <= 900:
|
||||
return total2
|
||||
if total2 > 900 and total1 <= 900:
|
||||
return total1
|
||||
|
||||
# 兜底:谁能解析就用谁;都不行则做进位
|
||||
if total1 is not None:
|
||||
return total1
|
||||
if total2 is not None:
|
||||
return total2
|
||||
|
||||
mm, ss = a, b
|
||||
mm += ss // 60
|
||||
ss = ss % 60
|
||||
return mm * 60 + ss
|
||||
|
||||
if len(digits) == 3:
|
||||
mm = int(digits[0])
|
||||
ss = int(digits[1:])
|
||||
if ss >= 60:
|
||||
# 例如 159 可能是 15:09(OCR 丢 0)
|
||||
mm2 = int(digits[:2])
|
||||
ss2 = int(digits[2])
|
||||
if ss2 < 60:
|
||||
return mm2 * 60 + ss2
|
||||
mm += ss // 60
|
||||
ss = ss % 60
|
||||
return mm * 60 + ss
|
||||
|
||||
if len(digits) == 2:
|
||||
return int(digits) # 直接当秒(更符合“临近开奖”场景)
|
||||
|
||||
if len(digits) == 1:
|
||||
return int(digits)
|
||||
|
||||
# 太长:取最后4位(OCR 常把别的数字也识别进来)
|
||||
tail = digits[-4:]
|
||||
a = int(tail[:2])
|
||||
b = int(tail[2:])
|
||||
if b >= 60 and a < 60:
|
||||
a, b = b, a
|
||||
if b >= 60:
|
||||
a += b // 60
|
||||
b = b % 60
|
||||
return a * 60 + b
|
||||
|
||||
try:
|
||||
total_seconds = _parse_seconds(last_time)
|
||||
if total_seconds is None:
|
||||
_uo_log("时间格式异常")
|
||||
return False
|
||||
_uo_log("剩余总秒数:", total_seconds)
|
||||
# 超过 15 分钟基本是误识别:按 14分50秒处理,避免卡死等待
|
||||
if total_seconds > 900:
|
||||
total_seconds = 890
|
||||
|
||||
now = datetime.now()
|
||||
_uo_log("当前时间:", now.strftime("%Y-%m-%d %H:%M:%S"))
|
||||
future_time = now + timedelta(seconds=int(total_seconds))
|
||||
future_timestamp = future_time.timestamp()
|
||||
future_datetime = datetime.fromtimestamp(future_timestamp)
|
||||
formatted_future_time = future_datetime.strftime("%Y-%m-%d %H:%M:%S")
|
||||
_uo_log("预计开奖时间:", formatted_future_time)
|
||||
return int(total_seconds), future_timestamp
|
||||
except Exception:
|
||||
_uo_log("输入的字符串不是有效的时间格式")
|
||||
return False
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
"""underlying_operations_pkg.ocr_content - OCR 文本拼接 + 置信度。
|
||||
|
||||
extract_ocr_content: 把 OCR 引擎返回的多行结果拼成一段文本,
|
||||
可选附带置信度统计(avg/min/max/count)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def extract_ocr_content(content=None, return_confidence=False):
|
||||
"""对OCR识别到的内容进行取值和拼接,变成完整的一段内容
|
||||
|
||||
参数:
|
||||
content: OCR识别结果
|
||||
return_confidence: 是否返回置信度信息(默认False,保持向后兼容)
|
||||
|
||||
返回:
|
||||
如果return_confidence=False: 返回文本字符串
|
||||
如果return_confidence=True: 返回(text, confidence_info)元组,其中confidence_info是置信度信息字典
|
||||
"""
|
||||
ocr_result = content or []
|
||||
|
||||
# 用于收集置信度信息
|
||||
confidence_scores = []
|
||||
confidence_info = {
|
||||
"avg_confidence": 0.0,
|
||||
"min_confidence": 1.0,
|
||||
"max_confidence": 0.0,
|
||||
"item_count": 0,
|
||||
}
|
||||
|
||||
def _extract_text_and_confidence_from_item(item):
|
||||
"""提取文本和置信度"""
|
||||
text = ""
|
||||
confidence = None
|
||||
|
||||
# 兼容EasyOCR格式:[(bbox, text, confidence), ...] -> (bbox, text, confidence)
|
||||
if isinstance(item, (list, tuple)) and len(item) >= 2:
|
||||
# EasyOCR格式:item = (bbox, text, confidence),text在索引1,confidence在索引2
|
||||
if len(item) >= 3:
|
||||
confidence = item[2]
|
||||
if isinstance(item[1], str):
|
||||
text = item[1]
|
||||
return text, confidence
|
||||
|
||||
# 兼容旧格式:[box, (text, score)]
|
||||
second = item[1]
|
||||
if isinstance(second, (list, tuple)) and len(second) >= 1:
|
||||
if isinstance(second[0], str):
|
||||
return second[0]
|
||||
if isinstance(second, dict):
|
||||
for key in ("text", "rec_text", "transcription"):
|
||||
val = second.get(key)
|
||||
if isinstance(val, str) and val:
|
||||
return val
|
||||
if isinstance(second, str):
|
||||
return second
|
||||
|
||||
# 兼容新格式:dict / 对象
|
||||
if isinstance(item, dict):
|
||||
# 常见:rec_texts 为字符串列表
|
||||
for list_key in ("rec_texts", "texts", "text_list"):
|
||||
vals = item.get(list_key)
|
||||
if isinstance(vals, list) and vals:
|
||||
vals = [v for v in vals if isinstance(v, str) and v]
|
||||
if vals:
|
||||
return "".join(vals)
|
||||
for key in ("text", "rec_text", "transcription"):
|
||||
val = item.get(key)
|
||||
if isinstance(val, str) and val:
|
||||
return val
|
||||
|
||||
for attr in ("text", "rec_text", "transcription"):
|
||||
val = getattr(item, attr, None)
|
||||
if isinstance(val, str) and val:
|
||||
return val
|
||||
|
||||
# 对象属性里也可能是列表
|
||||
for list_attr in ("rec_texts", "texts", "text_list"):
|
||||
vals = getattr(item, list_attr, None)
|
||||
if isinstance(vals, list) and vals:
|
||||
vals = [v for v in vals if isinstance(v, str) and v]
|
||||
if vals:
|
||||
return "".join(vals)
|
||||
|
||||
return ""
|
||||
|
||||
# PaddleOCR 可能返回 [[...]] 或 [...]
|
||||
items = ocr_result
|
||||
if (
|
||||
isinstance(ocr_result, list)
|
||||
and len(ocr_result) == 1
|
||||
and isinstance(ocr_result[0], list)
|
||||
):
|
||||
items = ocr_result[0]
|
||||
|
||||
def _extract_xy_from_item(item):
|
||||
"""尽力从 OCR item 中提取用于排序的 (y, x)。无法提取则返回 None。"""
|
||||
try:
|
||||
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 = []
|
||||
for p in box:
|
||||
if isinstance(p, (list, tuple)) and len(p) >= 2:
|
||||
xs.append(float(p[0]))
|
||||
ys.append(float(p[1]))
|
||||
if xs and ys:
|
||||
return (min(ys), min(xs))
|
||||
except Exception:
|
||||
return None
|
||||
return None
|
||||
|
||||
def _extract_text_from_item(item):
|
||||
"""提取文本(原始逻辑,保持向后兼容)"""
|
||||
# 兼容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):
|
||||
return second[0]
|
||||
if isinstance(second, dict):
|
||||
for key in ("text", "rec_text", "transcription"):
|
||||
val = second.get(key)
|
||||
if isinstance(val, str) and val:
|
||||
return val
|
||||
if isinstance(second, str):
|
||||
return second
|
||||
|
||||
# 兼容新格式:dict / 对象
|
||||
if isinstance(item, dict):
|
||||
# 常见:rec_texts 为字符串列表
|
||||
for list_key in ("rec_texts", "texts", "text_list"):
|
||||
vals = item.get(list_key)
|
||||
if isinstance(vals, list) and vals:
|
||||
vals = [v for v in vals if isinstance(v, str) and v]
|
||||
if vals:
|
||||
return "".join(vals)
|
||||
for key in ("text", "rec_text", "transcription"):
|
||||
val = item.get(key)
|
||||
if isinstance(val, str) and val:
|
||||
return val
|
||||
|
||||
for attr in ("text", "rec_text", "transcription"):
|
||||
val = getattr(item, attr, None)
|
||||
if isinstance(val, str) and val:
|
||||
return val
|
||||
|
||||
# 对象属性里也可能是列表
|
||||
for list_attr in ("rec_texts", "texts", "text_list"):
|
||||
vals = getattr(item, list_attr, None)
|
||||
if isinstance(vals, list) and vals:
|
||||
vals = [v for v in vals if isinstance(v, str) and v]
|
||||
if vals:
|
||||
return "".join(vals)
|
||||
|
||||
return ""
|
||||
|
||||
extracted_items = []
|
||||
if isinstance(items, list):
|
||||
for idx, item in enumerate(items):
|
||||
text = _extract_text_from_item(item)
|
||||
if not text:
|
||||
continue
|
||||
xy = _extract_xy_from_item(item)
|
||||
if xy is None:
|
||||
# 无坐标信息:保持原相对顺序
|
||||
extracted_items.append((1e18, float(idx), text))
|
||||
else:
|
||||
y, x = xy
|
||||
extracted_items.append((float(y), float(x), text))
|
||||
|
||||
# 按从上到下、从左到右排序;解决同一行多个框的乱序拼接(例如倒计时两段数字)
|
||||
extracted_items.sort(key=lambda t: (t[0], t[1]))
|
||||
|
||||
# 如果不需要返回置信度,直接返回文本(保持向后兼容)
|
||||
if not return_confidence:
|
||||
return "".join([t[2] for t in extracted_items])
|
||||
|
||||
# 如果需要返回置信度,提取置信度信息
|
||||
if return_confidence:
|
||||
for item in items:
|
||||
confidence = None
|
||||
# EasyOCR格式:[(bbox, text, confidence), ...]
|
||||
if isinstance(item, (list, tuple)) and len(item) >= 3:
|
||||
confidence = item[2]
|
||||
# PaddleOCR格式:[box, (text, score)]
|
||||
elif isinstance(item, (list, tuple)) and len(item) >= 2:
|
||||
second = item[1]
|
||||
if isinstance(second, (list, tuple)) and len(second) >= 2:
|
||||
confidence = second[1]
|
||||
elif isinstance(second, dict):
|
||||
confidence = second.get("confidence") or second.get("score")
|
||||
|
||||
if confidence is not None:
|
||||
try:
|
||||
conf_float = float(confidence)
|
||||
confidence_scores.append(conf_float)
|
||||
confidence_info["min_confidence"] = min(
|
||||
confidence_info["min_confidence"], conf_float
|
||||
)
|
||||
confidence_info["max_confidence"] = max(
|
||||
confidence_info["max_confidence"], conf_float
|
||||
)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
if confidence_scores:
|
||||
confidence_info["avg_confidence"] = sum(confidence_scores) / len(
|
||||
confidence_scores
|
||||
)
|
||||
confidence_info["item_count"] = len(confidence_scores)
|
||||
else:
|
||||
confidence_info["min_confidence"] = 0.0
|
||||
|
||||
return "".join([t[2] for t in extracted_items]), confidence_info
|
||||
|
||||
return "".join([t[2] for t in extracted_items])
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
"""underlying_operations_pkg.pic_path - 图片路径查找(含新旧位置兼容)。
|
||||
|
||||
_find_pic_path: 按图片名查找路径。运行时必需文件(screenshot/cut)放在
|
||||
``pic/`` 根;OCR 调试图片按 douyin_screenshot_manager 分类组织到子目录。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import Optional
|
||||
|
||||
|
||||
def _find_pic_path(picname: str, for_reading: bool = True) -> Optional[str]:
|
||||
"""查找图片路径,支持新旧位置(向后兼容),并按分类组织
|
||||
|
||||
Args:
|
||||
picname: 图片名称(不含扩展名),如 '直播广场', '福袋内容'
|
||||
for_reading: True=读取(支持新旧位置),False=写入(使用新位置+分类目录)
|
||||
|
||||
Returns:
|
||||
图片的完整路径,如果找不到且for_reading=True则返回None
|
||||
"""
|
||||
try:
|
||||
from douyin.core import path_config
|
||||
|
||||
pic_base = path_config.get_pic_dir()
|
||||
except Exception:
|
||||
from douyin.core import path_config
|
||||
|
||||
pic_base = path_config.get_pic_dir()
|
||||
|
||||
# 运行时必需文件始终在根目录(不需要移动)
|
||||
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图片文件:按分类组织到子目录
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
category = douyin_screenshot_manager.get_category_for_picname(picname)
|
||||
except Exception:
|
||||
category = "others"
|
||||
|
||||
if for_reading:
|
||||
# 读取:先查分类目录,再查旧位置(向后兼容)
|
||||
# 1. 新位置(分类目录)
|
||||
category_path = os.path.join(pic_base, "ocr", category, f"{picname}.png")
|
||||
if os.path.exists(category_path):
|
||||
return category_path
|
||||
# 2. 旧位置(ocr根目录)
|
||||
old_ocr_path = os.path.join(pic_base, "ocr", f"{picname}.png")
|
||||
if os.path.exists(old_ocr_path):
|
||||
return old_ocr_path
|
||||
# 3. 更旧的位置(pic根目录)
|
||||
old_root_path = os.path.join(pic_base, f"{picname}.png")
|
||||
if os.path.exists(old_root_path):
|
||||
return old_root_path
|
||||
return None
|
||||
else:
|
||||
# 写入:使用分类目录,确保目录存在
|
||||
category_dir = os.path.join(pic_base, "ocr", category)
|
||||
os.makedirs(category_dir, exist_ok=True)
|
||||
return os.path.join(category_dir, f"{picname}.png")
|
||||
|
||||
Reference in new issue
Block a user