20250904-初步功能已完成
This commit is contained in:
140
Utils/AiUtils.py
140
Utils/AiUtils.py
@@ -1,7 +1,11 @@
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
import unicodedata
|
||||
import wda
|
||||
from Utils.LogManager import LogManager
|
||||
import xml.etree.ElementTree as ET
|
||||
@@ -294,7 +298,6 @@ class AiUtils(object):
|
||||
print(f"btn:{btn}")
|
||||
return cls.findNumber(btn.label)
|
||||
|
||||
|
||||
@classmethod
|
||||
def extract_messages_from_xml(cls, xml: str):
|
||||
"""
|
||||
@@ -304,7 +307,6 @@ class AiUtils(object):
|
||||
root = etree.fromstring(xml.encode("utf-8"))
|
||||
items = []
|
||||
|
||||
|
||||
# 屏幕宽度
|
||||
app = root.xpath('/XCUIElementTypeApplication')
|
||||
screen_w = cls.parse_float(app[0], 'width', 414.0) if app else 414.0
|
||||
@@ -474,3 +476,137 @@ class AiUtils(object):
|
||||
# 使用正则表达式匹配中文字符
|
||||
pattern = re.compile(r'[\u4e00-\u9fff]')
|
||||
return bool(pattern.search(text))
|
||||
|
||||
@classmethod
|
||||
def is_language(cls, text: str) -> bool:
|
||||
if not text:
|
||||
return False
|
||||
for ch in text:
|
||||
if unicodedata.category(ch).startswith("L"):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
@classmethod
|
||||
def _read_json_list(cls, file_path: Path) -> list:
|
||||
"""读取为 list;读取失败或不是 list 则返回空数组"""
|
||||
if not file_path.exists():
|
||||
return []
|
||||
try:
|
||||
with open(file_path, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
return data if isinstance(data, list) else []
|
||||
except Exception as e:
|
||||
LogManager.error(f"[acList] 读取失败,将按空数组处理: {e}")
|
||||
return []
|
||||
|
||||
@classmethod
|
||||
def _write_json_list(cls, file_path: Path, data: list) -> None:
|
||||
file_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(file_path, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=2)
|
||||
|
||||
@staticmethod
|
||||
def _normalize_anchor_items(items):
|
||||
"""
|
||||
规范化输入为 [{anchorId, country}] 的列表:
|
||||
- 允许传入:单个对象、对象列表、字符串(当 anchorId 用)
|
||||
- 过滤不合规项
|
||||
"""
|
||||
result = []
|
||||
if items is None:
|
||||
return result
|
||||
|
||||
if isinstance(items, dict):
|
||||
# 单个对象
|
||||
aid = items.get("anchorId")
|
||||
if aid:
|
||||
result.append({"anchorId": str(aid), "country": items.get("country", "")})
|
||||
return result
|
||||
|
||||
if isinstance(items, list):
|
||||
for it in items:
|
||||
if isinstance(it, dict):
|
||||
aid = it.get("anchorId")
|
||||
if aid:
|
||||
result.append({"anchorId": str(aid), "country": it.get("country", "")})
|
||||
elif isinstance(it, str):
|
||||
result.append({"anchorId": it, "country": ""})
|
||||
return result
|
||||
|
||||
if isinstance(items, str):
|
||||
result.append({"anchorId": items, "country": ""})
|
||||
return result
|
||||
|
||||
# -------- 追加(对象数组平铺追加) --------
|
||||
@classmethod
|
||||
def save_aclist_flat_append(cls, acList, filename="log/acList.json"):
|
||||
"""
|
||||
将 anchor 对象数组平铺追加到 JSON 文件(数组)中。
|
||||
期望 acList 形如:
|
||||
[
|
||||
{"anchorId": "ldn327_", "country": ""},
|
||||
{"anchorId": "tianliang30", "country": ""}
|
||||
]
|
||||
"""
|
||||
file_path = Path(filename)
|
||||
data = cls._read_json_list(file_path)
|
||||
|
||||
# 规范化输入,确保都是 {anchorId, country}
|
||||
to_add = cls._normalize_anchor_items(acList)
|
||||
if not to_add:
|
||||
LogManager.info("[acList] 传入为空或不合规,跳过写入")
|
||||
return
|
||||
|
||||
data.extend(to_add)
|
||||
cls._write_json_list(file_path, data)
|
||||
LogManager.info(f"[acList] 已追加 {len(to_add)} 条,当前总数={len(data)} -> {file_path}")
|
||||
|
||||
# -------- 弹出(取一个删一个) --------
|
||||
@classmethod
|
||||
def pop_aclist_first(cls, filename="log/acList.json"):
|
||||
"""
|
||||
从 JSON 数组中取出第一个 anchor 对象,并删除它;为空或文件不存在返回 None。
|
||||
返回形如:{"anchorId": "...", "country": "..."}
|
||||
"""
|
||||
file_path = Path(filename)
|
||||
data = cls._read_json_list(file_path)
|
||||
if not data:
|
||||
return None
|
||||
|
||||
first = data.pop(0)
|
||||
# 兜底保证结构
|
||||
norm = cls._normalize_anchor_items(first)
|
||||
first = norm[0] if norm else None
|
||||
|
||||
cls._write_json_list(file_path, data)
|
||||
return first
|
||||
|
||||
@classmethod
|
||||
def delete_anchors_by_ids(cls, ids: list[str], filename="log/acList.json") -> int:
|
||||
"""
|
||||
根据 anchorId 列表从 JSON 文件中删除匹配的 anchor。
|
||||
返回删除数量。
|
||||
"""
|
||||
file_path = Path(filename)
|
||||
if not file_path.exists():
|
||||
return 0
|
||||
try:
|
||||
with open(file_path, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
if not isinstance(data, list):
|
||||
return 0
|
||||
except Exception as e:
|
||||
LogManager.error(f"[delete_anchors_by_ids] 读取失败: {e}")
|
||||
return 0
|
||||
before = len(data)
|
||||
# 保留不在 ids 里的对象
|
||||
data = [d for d in data if isinstance(d, dict) and d.get("anchorId") not in ids]
|
||||
deleted = before - len(data)
|
||||
try:
|
||||
with open(file_path, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=2)
|
||||
except Exception as e:
|
||||
LogManager.error(f"[delete_anchors_by_ids] 写入失败: {e}")
|
||||
return deleted
|
||||
|
||||
|
||||
Reference in New Issue
Block a user