From 2aa0aec99a72e7f7923ad37082058bce36284f00 Mon Sep 17 00:00:00 2001 From: Your Name Date: Sat, 3 Jan 2026 11:34:24 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=E4=BB=BB=E5=8A=A1?= =?UTF-8?q?=E5=88=97=E8=A1=A8OCR=E5=BC=80=E5=85=B3=EF=BC=8C=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E9=85=8D=E7=BD=AE=E4=B8=8E=E6=97=A5=E5=BF=97=E8=AE=B0?= =?UTF-8?q?=E5=BD=95=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/config.json | 3 +- docs/完整技术文档.md | 52 +++++++++++++ douyin/core/state/reservations.json | 2 +- douyin/fudai/core/fudai_detail_reader.py | 37 +++++++-- douyin/fudai/douyin_fudai_core.py | 96 +++++++++++++++++++++++- douyin/logging/action_logger.py | 15 +++- douyin/logging/douyin_logging_wrapper.py | 20 ++++- douyin/logging/log_formatter.py | 67 +++++++++++++++-- gui/gui_app.py | 18 +++++ 9 files changed, 290 insertions(+), 20 deletions(-) diff --git a/config/config.json b/config/config.json index 7cc24ba..e56c108 100644 --- a/config/config.json +++ b/config/config.json @@ -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 } diff --git a/docs/完整技术文档.md b/docs/完整技术文档.md index c43aa25..c075994 100644 --- a/docs/完整技术文档.md +++ b/docs/完整技术文档.md @@ -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('') +# 对单张图运行 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()`。 diff --git a/douyin/core/state/reservations.json b/douyin/core/state/reservations.json index d093919..5b06447 100644 --- a/douyin/core/state/reservations.json +++ b/douyin/core/state/reservations.json @@ -1,5 +1,5 @@ { - "updated_ts": 1767410552.1208727, + "updated_ts": 1767411026.6766307, "reason": "startup_clear", "room_pos": 0, "current_room_title": "", diff --git a/douyin/fudai/core/fudai_detail_reader.py b/douyin/fudai/core/fudai_detail_reader.py index 0090ebf..b4ec83a 100644 --- a/douyin/fudai/core/fudai_detail_reader.py +++ b/douyin/fudai/core/fudai_detail_reader.py @@ -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() diff --git a/douyin/fudai/douyin_fudai_core.py b/douyin/fudai/douyin_fudai_core.py index 01dc6cf..3a1d1a2 100644 --- a/douyin/fudai/douyin_fudai_core.py +++ b/douyin/fudai/douyin_fudai_core.py @@ -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: diff --git a/douyin/logging/action_logger.py b/douyin/logging/action_logger.py index 143b473..947668a 100644 --- a/douyin/logging/action_logger.py +++ b/douyin/logging/action_logger.py @@ -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: diff --git a/douyin/logging/douyin_logging_wrapper.py b/douyin/logging/douyin_logging_wrapper.py index 796192f..1facd28 100644 --- a/douyin/logging/douyin_logging_wrapper.py +++ b/douyin/logging/douyin_logging_wrapper.py @@ -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 重复 diff --git a/douyin/logging/log_formatter.py b/douyin/logging/log_formatter.py index 4d9d479..8b5195e 100644 --- a/douyin/logging/log_formatter.py +++ b/douyin/logging/log_formatter.py @@ -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: diff --git a/gui/gui_app.py b/gui/gui_app.py index 8747685..5e3ddcc 100644 --- a/gui/gui_app.py +++ b/gui/gui_app.py @@ -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 )