feat: 添加任务列表OCR开关,更新配置与日志记录功能

This commit is contained in:
Your Name committed 2026-01-03 11:34:24 +08:00
1 parent 4f74a5e95a
commit 2aa0aec99a
9 files changed
+290 -20

No files matched your search

+2 -1
View File
@@ -148,5 +148,6 @@
"fansclub_click_delay": 0.6,
"fansclub_auto_join_wait_seconds": 5.0,
"fansclub_manual_wait_seconds": 3.0,
"enable_streaming_screenshot": false
"enable_streaming_screenshot": false,
"fudai_exit_after_misses": 30
}
+52
View File
@@ -197,6 +197,58 @@ assert os.path.isdir(os.path.dirname(get_reservations_path()))
PY
```
## AI 集成指南(供代码助手/分析器使用)
目标:为自动化助手或 LLM 提供结构化入口与可观测点,便于自动查询、故障定位与代码导航。
- 项目意图(一句话):自动化在抖音直播中查找并参与“福袋”活动的流程化机器人,包含截图、像素/模板检测、OCR、决策与预约管理。
- 关键入口(按优先级):
- `run_cli.py`:CLI 入口,生成 `fudai_analyse` 实例并开始主循环;适合触发最小可运行示例。
- `douyin/core/douyin_fudai.py::fudai_choujiang()`:主循环调度;查看运行状态与错误堆栈。
- `Underlying_Operations.py`:底层设备接口(截图、裁剪、OCR)— 对外数据采集点。
- 可调用的“程序式”API(Python)示例:
```python
from Underlying_Operations import underlying_operations
op = underlying_operations()
# 获取当前截图路径
img = op.get_screenshot('<ADB_ID>')
# 对单张图运行 OCR
text = op.analyse_pic_word(img)
```
- 关键文件与含义速查表(便于 LLM 快速定位实现细节):
- `path_config.py`:统一路径(logs/pic/state)——用于定位运行数据。
- `douyin/logging/douyin_logging_wrapper.py`:业务日志封装——搜索 `traceId` 与 `stage`。
- `douyin/fudai/douyin_fudai_core.py`:业务决策与福袋解析。
- 可观测数据(建议供 AI 检索):
- 截图目录:`pic/`(按时间戳与文件名可映射运行步骤)。
- 行为日志:`logs/actions.log`(操作事件序列)。
- 统一日志:`logs/unified_*.log`(错误堆栈、traceId)。
- 工具产物:`tools/coords_report.csv`(硬编码坐标候选)。
- 配置/状态快速定位:
- 运行时配置:`config/config.json`(AI 可读取以模拟运行参数)。
- 状态文件:`state/reservations.json`(预约队列快照)。
- 推荐的自动分析任务(便于 LLM 自动执行或生成报告):
1. 检查最近 `logs/unified_*.log` 中的 ERROR/WARN,提取 `traceId` 与相关文件路径。
2. 对应 `traceId` 检索 `pic/` 中同时间窗口的截图,生成 OCR 对比表(识别结果 vs 预期)。
3. 从 `tools/coords_report.csv` 筛选出现频率高的文件/行,给出重构建议(提取到 `path_config` 或使用缩放函数)。
- 示例 LLM 提示模板(短):
"给定 `traceId:XYZ`,请从 `logs/unified_*.log` 中提取错误堆栈,定位触发点对应的源码文件与行数,并生成 3 条可能的修复建议(每条含修改位置与简要代码片段)。"
- 采集数据权限与安全:自动化助手读取日志与截图即可完成大部分分析;若需要访问远程设备或私有数据,请确保遵守隐私与访问控制策略,避免将敏感截图提交到远端模型。
此节旨在让 AI 快速找到“能运行的代码路径”与“可用于证据收集的文件”,从而降低人工解释成本并提高定位效率。
完成以上更新后,可考虑把常用查询脚本(例如从日志到截图的映射器)加入 `tools/` 以便自动执行。
6) 参考实现与文件链接
- 截图与裁剪:`Underlying_Operations.get_screenshot()`、`Underlying_Operations.cut_pic()`。
+1 -1
View File
@@ -1,5 +1,5 @@
{
"updated_ts": 1767410552.1208727,
"updated_ts": 1767411026.6766307,
"reason": "startup_clear",
"room_pos": 0,
"current_room_title": "",
+32 -5
View File
@@ -447,6 +447,27 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
except Exception:
pass
# 读取任务列表OCR开关
try:
disable_task_recognition = bool(
getattr(analyser, "fudai_disable_task_recognition", False)
)
except Exception:
disable_task_recognition = False
if not disable_task_recognition:
try:
import json
cfg_path = path_config.get_config_path()
if cfg_path and os.path.exists(cfg_path):
with open(cfg_path, "r", encoding="utf-8") as f:
cfg = json.load(f)
disable_task_recognition = bool(
cfg.get("fudai_disable_task_recognition", False)
)
except Exception:
pass
def ocr_task_list():
"""OCR识别任务列表(用于检测观看任务)"""
try:
@@ -558,7 +579,10 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
optimal_workers = get_optimal_workers()
with ThreadPoolExecutor(max_workers=optimal_workers) as executor:
future_task_list = executor.submit(ocr_task_list)
if disable_task_recognition:
future_task_list = None
else:
future_task_list = executor.submit(ocr_task_list)
# 有条件地提交 content OCR,避免在配置启用时仍然调度任务
if disable_content_recognition:
future_content = None
@@ -569,7 +593,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
future_value = executor.submit(ocr_value)
# 等待所有操作完成
task_list_raw = future_task_list.result()
task_list_raw = future_task_list.result() if future_task_list else None
fudai_content_raw = future_content.result() if future_content else None
countdown_mm_raw = future_countdown_mm.result()
countdown_ss_raw = future_countdown_ss.result()
@@ -759,15 +783,18 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
optimal_workers = get_optimal_workers()
with ThreadPoolExecutor(max_workers=optimal_workers) as executor:
future_task_list = executor.submit(ocr_task_list_fallback)
if disable_task_recognition:
future_task_list = None
else:
future_task_list = executor.submit(ocr_task_list_fallback)
future_content = executor.submit(ocr_content_fallback)
future_countdown_mm = executor.submit(ocr_countdown_mm_fallback)
future_countdown_ss = executor.submit(ocr_countdown_ss_fallback)
future_value = executor.submit(ocr_value_fallback)
# 等待所有操作完成
task_list_raw = future_task_list.result()
fudai_content_raw = future_content.result()
task_list_raw = future_task_list.result() if future_task_list else None
fudai_content_raw = future_content.result() if future_content else None
countdown_mm_raw = future_countdown_mm.result()
countdown_ss_raw = future_countdown_ss.result()
value_raw = future_value.result()
+93 -3
View File
@@ -356,12 +356,41 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
return name
# 任务列表:用于兜底检测观看任务
if "task_list" in fields:
# 读取任务列表OCR开关(运行时读取 analyser 属性或 config.json)
try:
disable_task_recognition = bool(
getattr(analyser, "fudai_disable_task_recognition", False)
)
except Exception:
disable_task_recognition = False
if not disable_task_recognition:
try:
name_tl = _safe_preprocess("福袋任务列表")
results["task_list"] = analyser.operation.analyse_pic_word(name_tl, 1)
import json
cfg_path = path_config.get_config_path()
if cfg_path and os.path.exists(cfg_path):
with open(cfg_path, "r", encoding="utf-8") as f:
cfg = json.load(f)
disable_task_recognition = bool(
cfg.get("fudai_disable_task_recognition", False)
)
except Exception:
pass
if "task_list" in fields:
if disable_task_recognition:
try:
analyser._log_kv(
"福袋",
"跳过福袋任务列表OCR识别(配置启用)",
)
except Exception:
pass
else:
try:
name_tl = _safe_preprocess("福袋任务列表")
results["task_list"] = analyser.operation.analyse_pic_word(name_tl, 1)
except Exception:
pass
# 内容:使用更重的文本模型兜底
if "content" in fields:
@@ -666,6 +695,37 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
"""OCR识别任务列表(用于检测观看任务)"""
start = time.time()
try:
# 运行时读取开关,优先使用 analyser 属性,其次读取 config.json
try:
disable_task_recognition = bool(
getattr(analyser, "fudai_disable_task_recognition", False)
)
except Exception:
disable_task_recognition = False
if not disable_task_recognition:
try:
import json
cfg_path = path_config.get_config_path()
if cfg_path and os.path.exists(cfg_path):
with open(cfg_path, "r", encoding="utf-8") as f:
cfg = json.load(f)
disable_task_recognition = bool(
cfg.get("fudai_disable_task_recognition", False)
)
except Exception:
pass
if disable_task_recognition:
try:
analyser._log_kv(
"福袋",
"跳过福袋任务列表OCR识别(配置启用)",
)
except Exception:
pass
return None
name_tl = preprocess_for_ocr(analyser, "福袋任务列表")
return analyser.operation.analyse_pic_word(name_tl, 0)
except Exception as e_inner:
@@ -1191,6 +1251,36 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
def ocr_task_list_fallback():
try:
# 同样尊重开关
try:
disable_task_recognition = bool(
getattr(analyser, "fudai_disable_task_recognition", False)
)
except Exception:
disable_task_recognition = False
if not disable_task_recognition:
try:
import json
cfg_path = path_config.get_config_path()
if cfg_path and os.path.exists(cfg_path):
with open(cfg_path, "r", encoding="utf-8") as f:
cfg = json.load(f)
disable_task_recognition = bool(
cfg.get("fudai_disable_task_recognition", False)
)
except Exception:
pass
if disable_task_recognition:
try:
analyser._log_kv(
"福袋",
"跳过备用福袋任务列表OCR识别(配置启用)",
)
except Exception:
pass
return None
name_tl2 = preprocess_for_ocr(analyser, "福袋任务列表")
return analyser.operation.analyse_pic_word(name_tl2, 0)
except Exception as e_inner2:
+14 -1
View File
@@ -79,7 +79,20 @@ class ActionLogger:
elapsed = kwargs.pop("elapsed", None)
if elapsed is None:
elapsed = 0.0
msg = format_action_log(operation, details or "", elapsed_seconds=elapsed, **kwargs)
try:
# 统一保留两位小数,便于日志阅读
elapsed_val = float(elapsed)
except Exception:
elapsed_val = 0.0
elapsed_rounded = round(elapsed_val, 2)
# 标记异常慢的操作(阈值可调整)
extra = dict(kwargs)
extra["elapsed_seconds"] = elapsed_rounded
if elapsed_val >= 10.0:
extra["slow"] = 1
msg = format_action_log(operation, details or "", **extra)
_logger.info(msg)
def log_ocr(self, region: str, result: str, elapsed: Optional[float] = None) -> None:
+17 -3
View File
@@ -583,8 +583,15 @@ class LoggingWrapper:
for h in root_logger.handlers
if isinstance(h, logging.StreamHandler) and h.stream == sys.stdout
]
# 保存原始级别并在 finally 中恢复,确保在异常路径也能正确还原
original_levels = {}
for handler in console_handlers:
handler.setLevel(logging.CRITICAL + 1) # 临时禁用
try:
original_levels[id(handler)] = getattr(handler, "level", logging.NOTSET)
handler.setLevel(logging.CRITICAL + 1) # 临时禁用
except Exception:
# 如果无法修改某个 handler,跳过但继续记录
continue
try:
if exc_info:
@@ -599,9 +606,16 @@ class LoggingWrapper:
level, log_message, extra={"caller": caller_info}
)
finally:
# 恢复控制台输出级别
# 恢复控制台输出级别到原始值,避免长期禁用
for handler in console_handlers:
handler.setLevel(logging.NOTSET)
try:
orig = original_levels.get(id(handler), logging.NOTSET)
handler.setLevel(orig)
except Exception:
try:
handler.setLevel(logging.NOTSET)
except Exception:
pass
elif hasattr(analyser, "_std_logger") and analyser._std_logger:
# 如果根 logger 没有 handlers,尝试使用 _std_logger(但通常不会到这里)
# 优化:跳过标准 logging 输出,避免与控制台 print 重复
+61 -6
View File
@@ -17,12 +17,67 @@ def format_debug_log(message: str, level: str = "DEBUG", tag: Optional[str] = No
return " ".join(parts)
def format_action_log(action: str, details: Optional[str] = None, **fields: Any) -> str:
base = f"[ACTION] {action}"
if details:
base += f" {details}"
if fields:
base += " " + " ".join(f"{k}={v}" for k, v in fields.items())
return base
"""
生成简洁的人类可读行为日志(优先中文),同时保留字段键值以便机器解析。
输出示例:
- 上滑切换直播间 耗时=2.10s
- 点击参与 福袋ID=123 value=200.0 slow=1
保留原始 key=value 形式以便下游解析器仍可使用。
"""
# 常用动作名称到中文的映射(可根据需要扩展)
action_name_map = {
"swipe_up_to_next_live": "上滑切换直播间",
"swipe_down_back_from_live": "下滑回退直播间",
"attend_choujiang": "点击参与抽奖",
"get_screenshot": "截屏",
"OCR": "OCR识别",
"Decision": "决策",
"Step": "步骤",
}
# 如果 action 表示通用类别(如 Step),把 details 映射为更友好的动作名
human_parts: list[str] = []
if action == "Step" and details:
human = action_name_map.get(details, details.replace("_", " "))
human_parts.append(human)
else:
human = action_name_map.get(action, action)
human_parts.append(human)
# 格式化 elapsed_seconds 为带单位的字符串(如果提供)
kv_parts: list[str] = []
elapsed = None
if "elapsed_seconds" in fields:
try:
elapsed = float(fields.pop("elapsed_seconds"))
except Exception:
elapsed = None
elif "elapsed" in fields:
try:
elapsed = float(fields.pop("elapsed"))
except Exception:
elapsed = None
if elapsed is not None:
kv_parts.append(f"耗时={round(elapsed,2)}s")
# 如果有 slow 标记,转换为中文提示
if "slow" in fields:
try:
if int(fields.pop("slow") or 0) == 1:
kv_parts.append("慢=1")
except Exception:
pass
# 剩余字段以 key=value 形式追加(保持紧凑,不换行)
for k, v in fields.items():
kv_parts.append(f"{k}={v}")
human_msg = " ".join(human_parts)
if kv_parts:
return f"[ACTION] {human_msg} " + " ".join(kv_parts)
return f"[ACTION] {human_msg}"
def format_error_log(message: str, level: str = "ERROR", tag: Optional[str] = None, **fields: Any) -> str:
+18
View File
@@ -424,6 +424,9 @@ def main():
fudai_disable_content_recognition_var = tk.BooleanVar(
value=bool(cfg.get("fudai_disable_content_recognition", False))
)
fudai_disable_task_recognition_var = tk.BooleanVar(
value=bool(cfg.get("fudai_disable_task_recognition", False))
)
fudai_exit_after_misses_var = tk.IntVar(
value=int(cfg.get("fudai_exit_after_misses", 30) or 30)
)
@@ -1237,6 +1240,15 @@ def main():
side=LEFT, padx=(6, 0)
)
# 任务列表 OCR 开关
ttk.Checkbutton(
row4c,
text="禁用福袋任务列表OCR识别",
variable=fudai_disable_task_recognition_var,
onvalue=True,
offvalue=False,
).pack(side=LEFT, padx=(12, 0))
row4e = ttk.Frame(fudai_find_box)
row4e.pack(fill=X, padx=10, pady=(0, 8))
ttk.Label(row4e, text="切换直播间后等待时间(秒):").pack(side=LEFT)
@@ -1599,6 +1611,9 @@ def main():
fudai_disable_content_recognition_var.set(
bool(cfg.get("fudai_disable_content_recognition", False))
)
fudai_disable_task_recognition_var.set(
bool(cfg.get("fudai_disable_task_recognition", False))
)
try:
fudai_exit_after_misses_var.set(
int(cfg.get("fudai_exit_after_misses", 30) or 30)
@@ -1825,6 +1840,9 @@ def main():
cfg2["fudai_disable_content_recognition"] = bool(
fudai_disable_content_recognition_var.get()
)
cfg2["fudai_disable_task_recognition"] = bool(
fudai_disable_task_recognition_var.get()
)
cfg2["switch_room_wait_after_stage_diag_seconds"] = float(
switch_room_wait_after_stage_diag_seconds_var.get() or 7.0
)