From 7b93413af7876d9b86125d62805e87885c40cb31 Mon Sep 17 00:00:00 2001 From: Your Name Date: Thu, 1 Jan 2026 11:30:59 +0800 Subject: [PATCH] =?UTF-8?q?=E5=9B=9E=E9=80=80=E5=88=B0=E7=9B=B4=E6=8E=A5?= =?UTF-8?q?=E6=88=AA=E5=9B=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Underlying_Operations.py | 131 +++++++++++++----- check_screenshot.py | 1 + check_screenshot_service_status.py | 1 + config/config.json | 8 +- docs/scrcpy_手动安装指南.md | 1 + docs/多线程优化实现总结.md | 1 + docs/多线程截图优化说明.md | 1 + docs/截图服务日志说明.md | 1 + docs/日志轮转功能说明.md | 1 + docs/测试验证指南.md | 1 + douyin/core/fudai_modules/base_interface.py | 1 + douyin/core/fudai_modules/fudai_room_utils.py | 1 + douyin/core/state/reservations.json | 2 +- douyin/detection/core/__init__.py | 1 + douyin/detection/douyin_detection.py | 19 ++- douyin/fudai/core/MODULARIZATION_PLAN.md | 1 + douyin/fudai/finder/__init__.py | 1 + douyin/handlers/douyin_screenshot_manager.py | 111 ++++++++++++++- douyin/logging/action_tracker.py | 1 + douyin/reservation/core/__init__.py | 1 + douyin_guaji.code-workspace | 1 + gui/components/__init__.py | 1 + gui/components/config_manager.py | 1 + gui/components/device_selector.py | 1 + gui/components/image_viewer.py | 1 + gui/components/log_color_config_fixed.py | 1 + gui/components/main_window.py | 1 + gui/components/ocr_panel.py | 1 + gui/gui_app.py | 12 ++ gui/web_components/__init__.py | 1 + gui/web_components/proc_runner.py | 1 + install_scrcpy.bat | 1 + manage_logs.py | 1 + operations/screenshot_operations.py | 16 ++- operations/screenshot_service.py | 51 +++++-- pyright_out.txt | Bin 78 -> 7720 bytes scripts/annotate_image.py | 63 +++++++++ test_ocr_multithread.py | 1 + test_parallel_ocr_quick.py | 1 + test_parallel_ocr_simple.py | 1 + tools/README_Region_Selector.md | 1 + 41 files changed, 380 insertions(+), 64 deletions(-) create mode 100644 scripts/annotate_image.py diff --git a/Underlying_Operations.py b/Underlying_Operations.py index 4d7c8e2..add07d0 100644 --- a/Underlying_Operations.py +++ b/Underlying_Operations.py @@ -540,8 +540,31 @@ class underlying_operations: if not os.path.exists(path0): return False sz = os.path.getsize(path0) - # PNG 通常远大于 1KB;0 字节/极小文件大概率是 adb 输出异常/中断 - return sz >= 1024 + if sz < 1024: + return False + # 额外校验 PNG 头与文件尾(快速检测截断) + try: + with open(path0, "rb") as _f: + header = _f.read(4) + if header != b"\x89PNG": + return False + try: + _f.seek(-256, 2) + except Exception: + _f.seek(0) + tail = _f.read(256) + if b"IEND" not in tail: + return False + except Exception: + return False + # 使用 PIL 验证文件完整性 + try: + from PIL import Image + with Image.open(path0) as im: + im.verify() + except Exception: + return False + return True except Exception: return False @@ -554,25 +577,55 @@ class underlying_operations: os.remove(tmp_file) except Exception: pass - with open(tmp_file, "wb") as f: - subprocess.run( - [adb, "-s", device_id, "exec-out", "screencap", "-p"], - stdout=f, - stderr=subprocess.DEVNULL, - check=True, - timeout=10, # 添加10秒超时,避免无限等待 - ) - if _valid_png(tmp_file): - # 使用安全的文件替换函数 - if _safe_replace_file(tmp_file, out_file): - _mirror_screenshot_to_external(out_file) - print(f"[{timetag}] [截图] ✓ 获取屏幕截图成功") - return True + try: + with open(tmp_file, "wb") as f: + subprocess.run( + [adb, "-s", device_id, "exec-out", "screencap", "-p"], + stdout=f, + stderr=subprocess.DEVNULL, + check=True, + timeout=10, # 添加10秒超时,避免无限等待 + ) + try: + f.flush() + os.fsync(f.fileno()) + except Exception: + pass + if _valid_png(tmp_file): + # 使用安全的文件替换函数 + if _safe_replace_file(tmp_file, out_file): + _mirror_screenshot_to_external(out_file) + # 最后再验一次目标文件,确保写入后可读 + try: + if _valid_png(out_file): + print(f"[{timetag}] [截图] ✓ 获取屏幕截图成功") + return True + else: + try: + st = os.stat(out_file) + print(f"[截图诊断] 目标文件验证失败: size={st.st_size}, mtime={st.st_mtime}") + except Exception: + pass + except Exception: + pass + else: + # 如果替换失败,但临时文件有效,记录诊断并重试回退方案 + try: + if os.path.exists(tmp_file): + st = os.stat(tmp_file) + print(f"[截图诊断] 临时文件存在但替换失败: tmp={tmp_file}, size={st.st_size}") + except Exception: + pass + # 继续尝试回退方案 else: - # 如果替换失败,但临时文件有效,仍然返回成功 - # 后续代码可以读取临时文件或重试 - print(f"[截图] 文件替换失败,但截图已保存到临时文件,将重试") - # 不立即返回,继续尝试回退方案 + # 临时文件本身无效,记录诊断信息 + try: + if os.path.exists(tmp_file): + st = os.stat(tmp_file) + print(f"[截图诊断] 临时文件无效: path={tmp_file}, size={st.st_size}") + except Exception: + pass + # 继续尝试回退方案 except subprocess.TimeoutExpired: # 超时异常,记录并继续重试 print(f"[截图] exec-out 超时,尝试重试或回退方案") @@ -618,8 +671,12 @@ class underlying_operations: # 使用安全的文件替换函数 if _safe_replace_file(tmp_file, out_file): _mirror_screenshot_to_external(out_file) - print("{} 获取屏幕截图".format(timetag)) - return True + try: + if _valid_png(out_file): + print("{} 获取屏幕截图".format(timetag)) + return True + except Exception: + pass else: # 如果替换失败,尝试最后一次:直接复制内容 try: @@ -629,15 +686,15 @@ class underlying_operations: if os.path.exists(tmp_file): # 尝试直接覆盖写入(如果文件被占用,这会失败,但至少尝试了) try: - with open(tmp_file, "rb") as src, open( - out_file, "wb" - ) as dst: + 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 + try: + if _valid_png(out_file): + print(f"[{timetag}] [截图] ✓ 获取屏幕截图成功(通过直接写入)") + return True + except Exception: + pass except (OSError, PermissionError) as e: # 如果还是失败,尝试将临时文件重命名为目标文件 try: @@ -653,17 +710,15 @@ class underlying_operations: # 尝试重命名临时文件为目标文件 os.rename(tmp_file, out_file) _mirror_screenshot_to_external(out_file) - print( - "{} 获取屏幕截图(通过重命名临时文件)".format( - timetag - ) - ) - return True + try: + if _valid_png(out_file): + print("{} 获取屏幕截图(通过重命名临时文件)".format(timetag)) + return True + except Exception: + pass except Exception: # 最后兜底:返回True,让调用者知道临时文件存在 - print( - f"[截图] 文件替换失败({e}),但截图已保存到临时文件 {tmp_file}" - ) + print(f"[截图] 文件替换失败({e}),但截图已保存到临时文件 {tmp_file}") return True except Exception: print(f"[截图] 文件替换失败,但截图已保存到临时文件 {tmp_file}") diff --git a/check_screenshot.py b/check_screenshot.py index d051cd3..387cd62 100644 --- a/check_screenshot.py +++ b/check_screenshot.py @@ -54,3 +54,4 @@ if __name__ == "__main__": + diff --git a/check_screenshot_service_status.py b/check_screenshot_service_status.py index 595bf8d..10b40e4 100644 --- a/check_screenshot_service_status.py +++ b/check_screenshot_service_status.py @@ -66,3 +66,4 @@ if __name__ == '__main__': + diff --git a/config/config.json b/config/config.json index fce9fc5..378d36a 100644 --- a/config/config.json +++ b/config/config.json @@ -77,7 +77,7 @@ "yanghao_like_keywords": [], "yanghao_fav_keywords": [], "stage_diag_max_time": 6.0, - "stage_diag_max_step_time": 2.0, + "stage_diag_max_step_time": 0.5, "live_room_match_threshold": 0.8, "enable_ocr_mode1": false, "fudai_template_match_enabled": false, @@ -141,5 +141,9 @@ "swipe_duration_ms": 300, "gui": { "theme": "litera" - } + }, + "fansclub_click_delay": 0.6, + "fansclub_auto_join_wait_seconds": 5.0, + "fansclub_manual_wait_seconds": 3.0, + "enable_streaming_screenshot": false } diff --git a/docs/scrcpy_手动安装指南.md b/docs/scrcpy_手动安装指南.md index 2d49062..52e155f 100644 --- a/docs/scrcpy_手动安装指南.md +++ b/docs/scrcpy_手动安装指南.md @@ -211,3 +211,4 @@ scrcpy --bit-rate=2M + diff --git a/docs/多线程优化实现总结.md b/docs/多线程优化实现总结.md index 32b871c..3368ade 100644 --- a/docs/多线程优化实现总结.md +++ b/docs/多线程优化实现总结.md @@ -205,3 +205,4 @@ python tools/check_system_config.py + diff --git a/docs/多线程截图优化说明.md b/docs/多线程截图优化说明.md index 2cc9c21..e171eb5 100644 --- a/docs/多线程截图优化说明.md +++ b/docs/多线程截图优化说明.md @@ -223,3 +223,4 @@ python tools/check_system_config.py + diff --git a/docs/截图服务日志说明.md b/docs/截图服务日志说明.md index 920e86e..19ead41 100644 --- a/docs/截图服务日志说明.md +++ b/docs/截图服务日志说明.md @@ -282,3 +282,4 @@ grep "缓存命中" logs/unified_*.log + diff --git a/docs/日志轮转功能说明.md b/docs/日志轮转功能说明.md index 84f141d..2fc0a82 100644 --- a/docs/日志轮转功能说明.md +++ b/docs/日志轮转功能说明.md @@ -193,3 +193,4 @@ unified_2024-01-15.1.log.gz # 压缩后的文件 + diff --git a/docs/测试验证指南.md b/docs/测试验证指南.md index dd2c4f9..5ee4be2 100644 --- a/docs/测试验证指南.md +++ b/docs/测试验证指南.md @@ -185,3 +185,4 @@ print(f"最后截图时间: {info['last_screenshot_time']}") + diff --git a/douyin/core/fudai_modules/base_interface.py b/douyin/core/fudai_modules/base_interface.py index 6cdf367..7d094d9 100644 --- a/douyin/core/fudai_modules/base_interface.py +++ b/douyin/core/fudai_modules/base_interface.py @@ -115,5 +115,6 @@ class BaseFudaiMixin: + diff --git a/douyin/core/fudai_modules/fudai_room_utils.py b/douyin/core/fudai_modules/fudai_room_utils.py index 8d53c23..8be4324 100644 --- a/douyin/core/fudai_modules/fudai_room_utils.py +++ b/douyin/core/fudai_modules/fudai_room_utils.py @@ -89,5 +89,6 @@ class RoomUtilsMixin: + diff --git a/douyin/core/state/reservations.json b/douyin/core/state/reservations.json index 229982a..e2dbd8e 100644 --- a/douyin/core/state/reservations.json +++ b/douyin/core/state/reservations.json @@ -1,5 +1,5 @@ { - "updated_ts": 1767232380.699456, + "updated_ts": 1767237576.577889, "reason": "startup_clear", "room_pos": 0, "current_room_title": "", diff --git a/douyin/detection/core/__init__.py b/douyin/detection/core/__init__.py index efa7edf..c5d9d32 100644 --- a/douyin/detection/core/__init__.py +++ b/douyin/detection/core/__init__.py @@ -61,5 +61,6 @@ __all__ = [ + diff --git a/douyin/detection/douyin_detection.py b/douyin/detection/douyin_detection.py index 56e5ce3..8e6b1b1 100644 --- a/douyin/detection/douyin_detection.py +++ b/douyin/detection/douyin_detection.py @@ -344,9 +344,26 @@ def check_have_fudai_with_ready_screenshot( "找福袋图标", "判定是否存在福袋", analyser.device_id, diagnose=False ) except Exception: - # 如果截图失败,尝试直接调用 get_screenshot + # 如果截图失败,尝试直接调用 get_screenshot 并验证文件可读性(避免半写入/截断图片导致后续 PIL 打开失败) try: analyser.operation.get_screenshot(analyser.device_id) + # 简单验证:文件存在、大小足够且能由 PIL 打开/加载 + valid = False + try: + if os.path.exists(pic1_path) and os.path.getsize(pic1_path) >= 1024: + from PIL import Image as PILImage + + with PILImage.open(pic1_path) as _im: + _im.verify() + valid = True + except Exception: + valid = False + if not valid: + # 再尝试一次直接截图作为最后回退 + try: + analyser.operation.get_screenshot(analyser.device_id) + except Exception: + pass except Exception: pass diff --git a/douyin/fudai/core/MODULARIZATION_PLAN.md b/douyin/fudai/core/MODULARIZATION_PLAN.md index d02ef5a..7d3305b 100644 --- a/douyin/fudai/core/MODULARIZATION_PLAN.md +++ b/douyin/fudai/core/MODULARIZATION_PLAN.md @@ -102,5 +102,6 @@ + diff --git a/douyin/fudai/finder/__init__.py b/douyin/fudai/finder/__init__.py index 7d01150..5dde97e 100644 --- a/douyin/fudai/finder/__init__.py +++ b/douyin/fudai/finder/__init__.py @@ -66,5 +66,6 @@ __all__ = [ + diff --git a/douyin/handlers/douyin_screenshot_manager.py b/douyin/handlers/douyin_screenshot_manager.py index 89c9956..88a82ea 100644 --- a/douyin/handlers/douyin_screenshot_manager.py +++ b/douyin/handlers/douyin_screenshot_manager.py @@ -985,17 +985,114 @@ def save_debug_image( # type: ignore ) draw.rectangle(rect_coords, outline="red", width=2) - # 添加文本信息 - if extra_info: - text_lines = [f"{k}: {v}" for k, v in extra_info.items()] - if text_lines: - text = "\n".join(text_lines) - # 在图像左上角添加文本 + # 添加文本信息:统一使用底部半透明信息栏,风格与 OCR 调试图一致 + try: + info_lines = [] + # 基础信息行:图片名 / 步骤 + if picname: + info_lines.append(str(_PICNAME_CN.get(picname, picname))) + if step: + info_lines.append(str(_STEP_CN.get(step, step))) + + # 坐标与额外信息优先展示重要字段 + if coords: + info_lines.append(f"coords: ({coords[0]},{coords[1]})-({coords[2]},{coords[3]})") + + if extra_info: + # 组织额外信息为若干行,按重要字段顺序展示 + important_keys = ["result", "detected_x", "detected_x_scaled", "match_score", "mode", "size", "avg_confidence", "text_preview"] + for key in important_keys: + if key in extra_info: + info_lines.append(f"{_EXTRA_INFO_KEY_CN.get(key, key)}: {extra_info.get(key)}") + # 将其余的键也加入(但限制长度) + for k, v in extra_info.items(): + if k in important_keys: + continue + # 限制文本长度,避免溢出 + s = str(v) + if len(s) > 30: + s = s[:30] + "..." + info_lines.append(f"{_EXTRA_INFO_KEY_CN.get(k, k)}: {s}") + + # 如果没有任何信息,则不绘制信息栏 + if info_lines: + # 准备RGBA图层以绘制半透明底栏 + if annotated_image.mode != "RGBA": + annotated_image = annotated_image.convert("RGBA") + overlay = Image.new("RGBA", annotated_image.size, (0, 0, 0, 0)) + odraw = ImageDraw.Draw(overlay) + + # 计算文字区域高度 + padding_v = 6 + padding_h = 8 + max_width = annotated_image.size[0] - padding_h * 2 + lines_to_draw = [] + for line in info_lines: + # 简单换行:如果太长,切断 + if font: + w, h = odraw.textsize(line, font=font) + else: + w, h = odraw.textsize(line) + if w > max_width: + # 估算每行能容纳的字符数并切断 + approx_chars = max(10, int(len(line) * max_width / max(w, 1))) + lines_to_draw.append(line[:approx_chars] + "...") + else: + lines_to_draw.append(line) + + line_height = 14 if font is None else (font.getsize("Ay")[1] if hasattr(font, "getsize") else 14) + bar_height = padding_v * 2 + line_height * len(lines_to_draw) + img_w, img_h = annotated_image.size + bar_y1 = img_h - bar_height + bar_y2 = img_h + + # 绘制半透明白色底栏 + odraw.rectangle([0, bar_y1, img_w, bar_y2], fill=(255, 255, 255, 200)) + + # 绘制文字(黑色) + text_x = padding_h + text_y = bar_y1 + padding_v + for line in lines_to_draw: + try: + odraw.text((text_x, text_y), line, fill=(10, 10, 10, 255), font=font) + except Exception: + try: + odraw.text((text_x, text_y), line, fill=(10, 10, 10, 255)) + except Exception: + pass + text_y += line_height + + # 如果 extra_info 中包含匹配坐标(match_coords)或检测像素坐标(detected_x_scaled),绘制点/框以便快速定位 try: - draw.text((5, 5), text, fill="yellow", font=font) + if extra_info: + # 模板匹配提供 match_coords 字段(tuple) + if "match_coords" in extra_info and isinstance(extra_info["match_coords"], (list, tuple)) and len(extra_info["match_coords"]) == 4: + mx1, my1, mx2, my2 = extra_info["match_coords"] + # 在 overlay 上画红框 + odraw.rectangle([mx1, my1, mx2, my2], outline=(255, 0, 0, 200), width=2) + # 像素检测提供 detected_x_scaled:图像坐标系中的x(单点),并依赖 coords 提供 y 区域 + elif "detected_x_scaled" in extra_info and coords: + try: + dx = int(extra_info["detected_x_scaled"]) + cy = (coords[1] + coords[3]) // 2 + r = max(4, int(min(annotated_image.size) * 0.01)) + odraw.ellipse([dx - r, cy - r, dx + r, cy + r], fill=(0, 128, 255, 220), outline=(0, 64, 192, 220)) + except Exception: + pass except Exception: pass + # 合并 overlay 到原图并保存 + try: + annotated_image = Image.alpha_composite(annotated_image, overlay) + # 转回 RGB 保存为PNG,以减少兼容问题 + annotated_image = annotated_image.convert("RGB") + except Exception: + pass + except Exception: + # 标注失败,回退到原有行为(什么也不画) + pass + save_image_with_retry(annotated_image, file_path) except (PermissionError, OSError) as e: # 权限或系统错误,尝试保存原图 diff --git a/douyin/logging/action_tracker.py b/douyin/logging/action_tracker.py index 774f427..1b4ca28 100644 --- a/douyin/logging/action_tracker.py +++ b/douyin/logging/action_tracker.py @@ -57,5 +57,6 @@ __all__ = ["track_action"] + diff --git a/douyin/reservation/core/__init__.py b/douyin/reservation/core/__init__.py index 18b69d5..35f73a7 100644 --- a/douyin/reservation/core/__init__.py +++ b/douyin/reservation/core/__init__.py @@ -76,5 +76,6 @@ __all__ = [ + diff --git a/douyin_guaji.code-workspace b/douyin_guaji.code-workspace index d159ebb..d728d0f 100644 --- a/douyin_guaji.code-workspace +++ b/douyin_guaji.code-workspace @@ -79,5 +79,6 @@ + diff --git a/gui/components/__init__.py b/gui/components/__init__.py index d98e125..66d648f 100644 --- a/gui/components/__init__.py +++ b/gui/components/__init__.py @@ -46,5 +46,6 @@ + diff --git a/gui/components/config_manager.py b/gui/components/config_manager.py index 69a9f3e..0dbfdb1 100644 --- a/gui/components/config_manager.py +++ b/gui/components/config_manager.py @@ -86,5 +86,6 @@ def save_ui_to_config( + diff --git a/gui/components/device_selector.py b/gui/components/device_selector.py index 1d3040a..70ec252 100644 --- a/gui/components/device_selector.py +++ b/gui/components/device_selector.py @@ -96,5 +96,6 @@ def create_device_selector( + diff --git a/gui/components/image_viewer.py b/gui/components/image_viewer.py index 2715904..66228ce 100644 --- a/gui/components/image_viewer.py +++ b/gui/components/image_viewer.py @@ -82,5 +82,6 @@ def create_image_viewer( + diff --git a/gui/components/log_color_config_fixed.py b/gui/components/log_color_config_fixed.py index 721a69c..c22dc81 100644 --- a/gui/components/log_color_config_fixed.py +++ b/gui/components/log_color_config_fixed.py @@ -207,3 +207,4 @@ def apply_operation_color( + diff --git a/gui/components/main_window.py b/gui/components/main_window.py index a205303..c277b4f 100644 --- a/gui/components/main_window.py +++ b/gui/components/main_window.py @@ -78,5 +78,6 @@ def create_main_window( + diff --git a/gui/components/ocr_panel.py b/gui/components/ocr_panel.py index 8fbcb58..e04c076 100644 --- a/gui/components/ocr_panel.py +++ b/gui/components/ocr_panel.py @@ -79,5 +79,6 @@ def create_ocr_panel( + diff --git a/gui/gui_app.py b/gui/gui_app.py index e2e804e..1e27022 100644 --- a/gui/gui_app.py +++ b/gui/gui_app.py @@ -1779,6 +1779,18 @@ def main(): write_config(cfg2) on_line("[配置] 已保存到 config.json") + # 如果用户关闭了流式后台截图,尝试停止正在运行的服务实例以立即生效 + try: + from operations.screenshot_service import ScreenshotService + if not bool(cfg2.get("enable_streaming_screenshot", True)): + try: + ScreenshotService.get_instance().stop() + on_line("[截图服务] 已停止后台流式截图(配置更新)") + except Exception: + on_line("[截图服务] 停止后台截图服务失败(请重启程序以确保生效)") + except Exception: + # ignore if service module not available + pass load_config_to_ui() diff --git a/gui/web_components/__init__.py b/gui/web_components/__init__.py index 0368f67..e827100 100644 --- a/gui/web_components/__init__.py +++ b/gui/web_components/__init__.py @@ -46,5 +46,6 @@ + diff --git a/gui/web_components/proc_runner.py b/gui/web_components/proc_runner.py index 7191218..f00e94d 100644 --- a/gui/web_components/proc_runner.py +++ b/gui/web_components/proc_runner.py @@ -54,5 +54,6 @@ __all__ = ["ProcRunner"] + diff --git a/install_scrcpy.bat b/install_scrcpy.bat index c1b3fff..1097c3f 100644 --- a/install_scrcpy.bat +++ b/install_scrcpy.bat @@ -125,3 +125,4 @@ goto :eof + diff --git a/manage_logs.py b/manage_logs.py index 71899ed..93ae5a2 100644 --- a/manage_logs.py +++ b/manage_logs.py @@ -255,3 +255,4 @@ if __name__ == "__main__": + diff --git a/operations/screenshot_operations.py b/operations/screenshot_operations.py index c71404b..4d369c3 100644 --- a/operations/screenshot_operations.py +++ b/operations/screenshot_operations.py @@ -15,6 +15,10 @@ from typing import Optional from Underlying_Operations import _safe_replace_file, _mirror_screenshot_to_external +# 日志节流:当后台服务不可用并回退到直接截图时,避免每次都打印相同的日志 +_last_service_fallback_log_ts: float = 0.0 +_SERVICE_FALLBACK_LOG_INTERVAL = 10.0 # seconds + class ScreenshotOperations: """截图操作类""" @@ -60,8 +64,12 @@ class ScreenshotOperations: if service_result: return True else: - timetag = datetime.now().strftime("%H:%M:%S") - print(f"[{timetag}] [截图操作] 后台服务未提供有效截图,回退到直接截图") + now = time.time() + global _last_service_fallback_log_ts + if now - _last_service_fallback_log_ts > _SERVICE_FALLBACK_LOG_INTERVAL: + timetag = datetime.now().strftime("%H:%M:%S") + print(f"[{timetag}] [截图操作] 后台服务未提供有效截图,回退到直接截图") + _last_service_fallback_log_ts = now return self._get_screenshot_direct(device_id, path) except Exception: # 如果服务调用抛出异常,回退到直接截图 @@ -177,7 +185,7 @@ class ScreenshotOperations: t_exec_end = time.time() exec_ms = (t_exec_end - t_exec_start) * 1000 timetag2 = datetime.now().strftime("%H:%M:%S") - print(f"[{timetag2}] [DEBUG] exec-out streaming duration: {exec_ms:.0f}ms (device_id={device_id})") + print(f"[{timetag2}] [DEBUG] exec-out duration: {exec_ms:.0f}ms (device_id={device_id})") except subprocess.TimeoutExpired: # Popen 超时,记录并重新抛出异常 @@ -188,7 +196,7 @@ class ScreenshotOperations: if _safe_replace_file(tmp_file, out_file): _mirror_screenshot_to_external(out_file) elapsed = (time.time() - direct_start) * 1000 - print(f"[{timetag}] [截图] [OK] 获取屏幕截图成功 (流式截图,耗时: {elapsed:.0f}ms)") + print(f"[{timetag}] [截图] [OK] 获取屏幕截图成功 (exec-out,耗时: {elapsed:.0f}ms)") return True else: # 如果替换失败,但临时文件有效,仍然返回成功 diff --git a/operations/screenshot_service.py b/operations/screenshot_service.py index 3de62da..8bb115d 100644 --- a/operations/screenshot_service.py +++ b/operations/screenshot_service.py @@ -17,7 +17,6 @@ from datetime import datetime from operations.screenshot_operations import ScreenshotOperations import json -import os import path_config @@ -50,6 +49,28 @@ class ScreenshotService: self._cache_valid_duration: float = 2.0 self._screenshot_path: Optional[str] = None self._last_success: bool = False + # 缓存配置读取结果以避免每次调用都读取文件并频繁打印相同日志 + self._streaming_enabled_cached: Optional[bool] = None + self._last_streaming_state_log_ts: float = 0.0 + self._last_streaming_check_ts: float = 0.0 + + def _check_streaming_enabled(self) -> bool: + """内部缓存检查配置,避免每次调用都读取文件。短时间内重复调用会复用缓存。""" + now = time.time() + # 刷新间隔:3 秒 + try: + if self._streaming_enabled_cached is None or (now - self._last_streaming_check_ts) > 3.0: + try: + enabled = _streaming_enabled() + except Exception: + enabled = True + self._streaming_enabled_cached = bool(enabled) + self._last_streaming_check_ts = now + except Exception: + # 任何异常时默认启用以不阻塞主流程 + self._streaming_enabled_cached = True + self._last_streaming_check_ts = now + return bool(self._streaming_enabled_cached) @classmethod def get_instance(cls) -> "ScreenshotService": @@ -61,9 +82,13 @@ class ScreenshotService: def start(self, device_id: str, interval: float = 1.5) -> None: """启动后台截图服务""" - if not _streaming_enabled(): + if not self._check_streaming_enabled(): timetag = datetime.now().strftime("%H:%M:%S") - print(f"[{timetag}] [截图服务] 流式后台截图已被禁用(config),忽略 start() 请求") + # 仅在状态变化或首次检测时打印日志,避免重复冗余信息 + now = time.time() + if now - self._last_streaming_state_log_ts > 30: + print(f"[{timetag}] [截图服务] 流式后台截图已被禁用(config),忽略 start() 请求") + self._last_streaming_state_log_ts = now return with self._lock: if self._running and self._current_device_id == device_id: @@ -76,8 +101,6 @@ class ScreenshotService: self._running = True try: - import path_config # local import to avoid import-time errors - self._screenshot_path = path_config.get_screenshot_path() except Exception: self._screenshot_path = os.path.join("pic", "screenshot.png") @@ -89,10 +112,6 @@ class ScreenshotService: print(f"[{timetag}] [截图服务] 已启动,device={device_id}, interval={self._screenshot_interval}s") def stop(self) -> None: - if not _streaming_enabled(): - timetag = datetime.now().strftime("%H:%M:%S") - print(f"[{timetag}] [截图服务] 流式后台截图已被禁用(config),忽略 stop() 请求") - return with self._lock: if not self._running: return @@ -146,9 +165,19 @@ class ScreenshotService: def get_screenshot(self, device_id: str, force: bool = False) -> bool: """尝试从缓存返回截图状态;否则执行直接截图回退""" - if not _streaming_enabled(): + if not self._check_streaming_enabled(): + # 如果配置关闭但后台线程仍在运行,尝试停止它(仅在需要时) + if self._running: + try: + self.stop() + except Exception: + pass timetag = datetime.now().strftime("%H:%M:%S") - print(f"[{timetag}] [截图服务] 流式后台截图被禁用(config),get_screenshot() 返回 False,调用方应回退到直接截图") + now = time.time() + # 节流:30 秒内只打印一次此日志,避免重复输出 + if now - self._last_streaming_state_log_ts > 30: + print(f"[{timetag}] [截图服务] 流式后台截图被禁用(config),get_screenshot() 返回 False,调用方应回退到直接截图") + self._last_streaming_state_log_ts = now return False if self._current_device_id != device_id: self.start(device_id) diff --git a/pyright_out.txt b/pyright_out.txt index 65a13188d93fd274521d0d399b3bbf7c54cd9e22..aa682cc2cb83cf8b82a817ba33f226972d76b43e 100644 GIT binary patch literal 7720 zcmeHM&rcIk5FR4YXkt8g^B@gL6D45i52*HnBwRcxA`qmtDW$(C-8S7Vv=I0ci(p2?wjw;eDh}B=C1&` z$wPyrQjk(Od&ow1a*-2f5B1@xN-@$XK}od7aZOW}qNI?I!npU-1X>*w#~nZ2F2k)L zdIu?ha}>RIO89n>xP)(I=`@`p3yy<3LN~DLrcNN`rYjg}2Y!rV3VNpS%tGsW-{-mX za{Ty6-qNfTkqAO-9}rWZr#06@7a$*m*4$6SY$yVikU*4Whaj6m%THr83CW9x3>`ag zsve(=>9OgCl{l%(5StbyAS@&Z%TOr-JJDc2QFvY0^ccAWM#lbiOqqfwn%$cijc({^ zcDz9f-xR1le35V<-2N@TJPf{YWZ zKx3BKicH4z{3~sys{(G>X)|VzOg1o#8(d=?r&|?Xz4)RtD!b!41*aQRFMgecm`aGs_;$T)COsdmfM;9|ap| zuo4d}R>2|HK5R#_e&dHl*WdH29}C-xQ&^01S4Nh;em(hdFmE}lM4_QZqoQ&d6IxE= z>=nNKVlkq(k1oYV^rtsgLO1nKgU<$XV1w)tN${!=k@jhcOfLQJt>VT_o0nIKoKp{pE}5M)UursZn7_?+7zu>;9_ MxrN<{9 delta 11 ScmZ2s" x1 y1 x2 y2 click_x click_y +Saves annotated image next to original with suffix "_annotated.png". +""" +import sys +from pathlib import Path + +try: + from PIL import Image, ImageDraw, ImageFont +except Exception: + print("Pillow not installed. Install with: pip install pillow") + raise + + +def annotate_image(src_path: Path, bbox, click_point, out_path: Path) -> None: + im = Image.open(src_path).convert("RGBA") + draw = ImageDraw.Draw(im) + x1, y1, x2, y2 = bbox + # rectangle + for i in range(4): + draw.rectangle((x1 - i, y1 - i, x2 + i, y2 + i), outline=(255, 0, 0, 200)) + # click point (circle) + cx, cy = click_point + r = max(6, int(min(im.size) * 0.01)) + draw.ellipse([cx - r, cy - r, cx + r, cy + r], fill=(0, 128, 255, 200)) + # label + try: + font = ImageFont.load_default() + except Exception: + font = None + label = f"bbox: ({x1},{y1})-({x2},{y2}) click: ({cx},{cy})" + text_pos = (x1, max(0, y1 - 14)) + draw.rectangle((text_pos[0], text_pos[1], text_pos[0] + 400, text_pos[1] + 14), fill=(0, 0, 0, 120)) + draw.text(text_pos, label, fill=(255, 255, 255, 255), font=font) + im.save(out_path) + print(f"Saved annotated image: {out_path}") + + +def main(): + if len(sys.argv) != 8: + print("Usage: python scripts/annotate_image.py x1 y1 x2 y2 click_x click_y") + sys.exit(2) + src = Path(sys.argv[1]) + if not src.exists(): + print("Source image not found (path may contain unicode or file missing)") + sys.exit(1) + try: + x1 = int(sys.argv[2]); y1 = int(sys.argv[3]); x2 = int(sys.argv[4]); y2 = int(sys.argv[5]) + cx = int(sys.argv[6]); cy = int(sys.argv[7]) + except Exception as e: + print("Invalid coordinates:", e) + sys.exit(1) + out = src.with_name(src.stem + "_annotated.png") + annotate_image(src, (x1, y1, x2, y2), (cx, cy), out) + + +if __name__ == "__main__": + main() + + diff --git a/test_ocr_multithread.py b/test_ocr_multithread.py index d65aa8e..dc78168 100644 --- a/test_ocr_multithread.py +++ b/test_ocr_multithread.py @@ -101,3 +101,4 @@ if __name__ == "__main__": + diff --git a/test_parallel_ocr_quick.py b/test_parallel_ocr_quick.py index 6b19aa5..b602320 100644 --- a/test_parallel_ocr_quick.py +++ b/test_parallel_ocr_quick.py @@ -142,3 +142,4 @@ if __name__ == "__main__": + diff --git a/test_parallel_ocr_simple.py b/test_parallel_ocr_simple.py index ab37de8..b043953 100644 --- a/test_parallel_ocr_simple.py +++ b/test_parallel_ocr_simple.py @@ -206,3 +206,4 @@ if __name__ == "__main__": main() + diff --git a/tools/README_Region_Selector.md b/tools/README_Region_Selector.md index 61bb5bd..e495b12 100644 --- a/tools/README_Region_Selector.md +++ b/tools/README_Region_Selector.md @@ -135,3 +135,4 @@ python region_selector.py path/to/image.png +