回退到直接截图
This commit is contained in:
1 parent
478ae69052
commit
7b93413af7
41 files changed
+380
-64
No files matched your search
+93
-38
@@ -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}")
|
||||
|
||||
@@ -54,3 +54,4 @@ if __name__ == "__main__":
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -66,3 +66,4 @@ if __name__ == '__main__':
|
||||
|
||||
|
||||
|
||||
|
||||
+6
-2
@@ -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
|
||||
}
|
||||
@@ -211,3 +211,4 @@ scrcpy --bit-rate=2M
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -205,3 +205,4 @@ python tools/check_system_config.py
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -223,3 +223,4 @@ python tools/check_system_config.py
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -282,3 +282,4 @@ grep "缓存命中" logs/unified_*.log
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -193,3 +193,4 @@ unified_2024-01-15.1.log.gz # 压缩后的文件
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -185,3 +185,4 @@ print(f"最后截图时间: {info['last_screenshot_time']}")
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -115,5 +115,6 @@ class BaseFudaiMixin:
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -89,5 +89,6 @@ class RoomUtilsMixin:
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"updated_ts": 1767232380.699456,
|
||||
"updated_ts": 1767237576.577889,
|
||||
"reason": "startup_clear",
|
||||
"room_pos": 0,
|
||||
"current_room_title": "",
|
||||
|
||||
@@ -61,5 +61,6 @@ __all__ = [
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -102,5 +102,6 @@
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -66,5 +66,6 @@ __all__ = [
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -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:
|
||||
# 权限或系统错误,尝试保存原图
|
||||
|
||||
@@ -57,5 +57,6 @@ __all__ = ["track_action"]
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -76,5 +76,6 @@ __all__ = [
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -79,5 +79,6 @@
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -46,5 +46,6 @@
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -86,5 +86,6 @@ def save_ui_to_config(
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -96,5 +96,6 @@ def create_device_selector(
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -82,5 +82,6 @@ def create_image_viewer(
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -207,3 +207,4 @@ def apply_operation_color(
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -78,5 +78,6 @@ def create_main_window(
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -79,5 +79,6 @@ def create_ocr_panel(
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -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()
|
||||
|
||||
|
||||
@@ -46,5 +46,6 @@
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -54,5 +54,6 @@ __all__ = ["ProcRunner"]
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -125,3 +125,4 @@ goto :eof
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -255,3 +255,4 @@ if __name__ == "__main__":
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -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:
|
||||
# 如果替换失败,但临时文件有效,仍然返回成功
|
||||
|
||||
@@ -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)
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Annotate an image with a bounding box and a click point.
|
||||
Usage:
|
||||
python scripts/annotate_image.py "<image_path>" 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 <image_path> 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()
|
||||
|
||||
|
||||
@@ -101,3 +101,4 @@ if __name__ == "__main__":
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -142,3 +142,4 @@ if __name__ == "__main__":
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -206,3 +206,4 @@ if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
|
||||
|
||||
@@ -135,3 +135,4 @@ python region_selector.py path/to/image.png
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user