Add fudai regression artifact collector

This commit is contained in:
Your Name committed 2026-06-19 02:03:29 +08:00
1 parent b850afae2c
commit 9c329caf72
6 files changed
+657 -7

No files matched your search

+2
View File
@@ -63,6 +63,8 @@ time_analysis_result.txt
# Test/diagnostic outputs
output/
artifacts/ocr_check/
artifacts/fudai_regression_runs/
artifacts/fudai_regression_samples/
artifacts/webui_checks/**/*.png
artifacts/webui_checks/**/*.txt
+69 -7
View File
@@ -4,6 +4,7 @@ import logging
import os
import shutil
import sys
import time
# ==== 将项目根目录加入 sys.path,确保后续所有 douyin.* 导入正常 ================
_BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@@ -341,14 +342,63 @@ def parse_args(argv: list[str]) -> argparse.Namespace:
default=None,
help="重新进入直播间点击模式:follow_list=关注列表坐标,screen_center=屏幕中心坐标",
)
p.add_argument(
"--disable-regression-collection",
action="store_true",
help="禁用运行结束自动收集福袋回归测试素材",
)
p.add_argument(
"--regression-collection-max-images",
type=int,
default=500,
help="运行结束最多保留本轮 debug capture 图片数(默认500,OCR图片按比例保留)",
)
return p.parse_args(argv)
def _collect_regression_artifacts_if_enabled(
args: argparse.Namespace,
*,
run_started_at: float,
exit_code: int | None,
device_id: str,
) -> None:
if bool(getattr(args, "disable_regression_collection", False)):
return
try:
from douyin.testing.regression_collector import (
build_run_id,
collect_run_regression_artifacts,
)
max_images = int(getattr(args, "regression_collection_max_images", 500) or 500)
max_images = max(1, max_images)
max_ocr_images = max(80, min(max_images, int(max_images * 0.4)))
result = collect_run_regression_artifacts(
run_id=build_run_id("run_cli"),
started_at=run_started_at,
exit_code=exit_code,
device_id=device_id,
max_debug_images=max_images,
max_ocr_images=max_ocr_images,
)
print(
"[REGRESSION] collected output_dir={} counts={}".format(
result.get("output_dir", ""),
result.get("counts", {}),
),
flush=True,
)
except Exception as e:
print("[REGRESSION] collect failed: {}".format(e), flush=True)
def main(argv: list[str]) -> int:
require_license_or_exit()
ensure_adb_in_path()
args = parse_args(argv)
run_started_at = time.time()
# 让命令行输出更稳定(实时刷新 + UTF-8)
try:
@@ -639,13 +689,25 @@ def main(argv: list[str]) -> int:
print("未检测到设备,退出。")
return 2
analyser.fudai_choujiang(
device_id=device_id,
y_pianyi=args.y_pianyi,
needswitch=bool(args.needswitch),
wait_minutes=int(args.wait_minutes),
)
return 0
exit_code = 0
try:
analyser.fudai_choujiang(
device_id=device_id,
y_pianyi=args.y_pianyi,
needswitch=bool(args.needswitch),
wait_minutes=int(args.wait_minutes),
)
except Exception:
exit_code = 1
raise
finally:
_collect_regression_artifacts_if_enabled(
args,
run_started_at=run_started_at,
exit_code=exit_code,
device_id=device_id,
)
return exit_code
if __name__ == "__main__":
+2
View File
@@ -0,0 +1,2 @@
"""Testing and regression artifact helpers."""
+398
View File
@@ -0,0 +1,398 @@
from __future__ import annotations
import json
import os
import shutil
import time
from pathlib import Path
from typing import Any
from douyin.core import path_config
DEFAULT_MAX_DEBUG_IMAGES = 200
DEFAULT_MAX_OCR_IMAGES = 80
DEFAULT_SCREENSHOT_CALLS_TAIL_LINES = 2000
DEFAULT_MAX_LOG_BYTES = 20 * 1024 * 1024
DEFAULT_MAX_LONG_TERM_SAMPLES_PER_CATEGORY = 5
LONG_TERM_SAMPLE_NOTES = {
"ui_position_swap_or_overlay": "可能是 UI 位置交换或遮挡:福袋 icon 位置与优惠券、购物红包或其他入口互换,不能直接归因成模板误识别。",
"miss_or_not_found": "未找到/漏检样本:用于确认画面明显有福袋但像素或模板未命中。",
"detail_stage_anomaly": "详情阶段异常样本:用于确认点开后阶段判断、详情页识别或弹层判断是否偏移。",
"attend_or_result_unknown": "参与或开奖结果未知样本:用于确认点击参与、等待开奖、中奖/未中奖识别链路。",
}
def _safe_name(value: str) -> str:
cleaned = "".join(ch if ch.isalnum() or ch in ("-", "_") else "_" for ch in value)
while "__" in cleaned:
cleaned = cleaned.replace("__", "_")
return cleaned.strip("_") or time.strftime("%Y%m%d_%H%M%S")
def _copy_file(src: Path, dst: Path) -> bool:
try:
if not src.exists() or not src.is_file():
return False
dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src, dst)
return True
except Exception:
return False
def _tail_text_file(src: Path, dst: Path, *, max_lines: int) -> bool:
try:
if not src.exists() or not src.is_file():
return False
lines: list[str] = []
with src.open("r", encoding="utf-8", errors="ignore") as f:
for line in f:
lines.append(line)
if len(lines) > max_lines:
del lines[: len(lines) - max_lines]
dst.parent.mkdir(parents=True, exist_ok=True)
dst.write_text("".join(lines), encoding="utf-8")
return True
except Exception:
return False
def _iter_recent_files(root: Path, *, since_ts: float, suffixes: tuple[str, ...]) -> list[Path]:
if not root.exists():
return []
found: list[Path] = []
try:
for path in root.rglob("*"):
if not path.is_file():
continue
if suffixes and path.suffix.lower() not in suffixes:
continue
try:
if path.stat().st_mtime + 0.001 < since_ts:
continue
except Exception:
continue
found.append(path)
except Exception:
return []
found.sort(key=lambda p: p.stat().st_mtime if p.exists() else 0.0)
return found
def _copy_recent_images(
*,
src_root: Path,
dst_root: Path,
since_ts: float,
max_images: int,
) -> list[str]:
files = _iter_recent_files(src_root, since_ts=since_ts, suffixes=(".png", ".jpg", ".jpeg"))
if max_images > 0 and len(files) > max_images:
files = files[-max_images:]
copied: list[str] = []
for src in files:
try:
rel = src.relative_to(src_root)
except Exception:
rel = Path(src.name)
dst = dst_root / rel
if _copy_file(src, dst):
copied.append(str(rel).replace("\\", "/"))
return copied
def _copy_run_logs(
root: Path,
out_dir: Path,
*,
since_ts: float,
screenshot_tail_lines: int,
) -> list[str]:
logs_dir = root / "logs"
copied: list[str] = []
if not logs_dir.exists():
return copied
patterns = (
"unified_*.log",
"detail_*.log",
"simple_*.log",
"actions.log",
)
for pattern in patterns:
for src in sorted(logs_dir.glob(pattern), key=lambda p: p.stat().st_mtime):
try:
if src.stat().st_mtime + 0.001 < since_ts:
continue
if src.stat().st_size > DEFAULT_MAX_LOG_BYTES and src.name != "actions.log":
continue
except Exception:
continue
dst = out_dir / "logs" / src.name
if _copy_file(src, dst):
copied.append(f"logs/{src.name}")
screenshot_calls = logs_dir / "screenshot_calls.jsonl"
if _tail_text_file(
screenshot_calls,
out_dir / "logs" / "screenshot_calls.tail.jsonl",
max_lines=screenshot_tail_lines,
):
copied.append("logs/screenshot_calls.tail.jsonl")
return copied
def _read_recent_log_text(root: Path, *, max_chars: int = 120_000) -> str:
logs_dir = root / "logs"
if not logs_dir.exists():
return ""
chunks: list[str] = []
for pattern in ("unified_*.log", "detail_*.log", "simple_*.log", "actions.log"):
for path in sorted(logs_dir.glob(pattern), key=lambda p: p.stat().st_mtime)[-6:]:
try:
text = path.read_text(encoding="utf-8", errors="ignore")
except Exception:
continue
chunks.append(text[-max_chars:])
return "\n".join(chunks)[-max_chars:]
def _classify_long_term_sample(path: Path, log_text: str) -> str | None:
name = path.name.lower()
lower_log = log_text.lower()
if any(
token in name
for token in (
"coupon",
"redpacket",
"false_left",
"shopping",
)
):
return "ui_position_swap_or_overlay"
if any(
token in name
for token in (
"miss",
"not_found",
"no_fudai",
)
):
return "miss_or_not_found"
if any(
token in name
for token in (
"detail_open_verdict",
"detail_not_recognized",
"detail_data_verdict",
"detail",
)
):
return "detail_stage_anomaly"
if any(
token in name
for token in (
"attend",
"lottery",
"result_unknown",
)
):
return "attend_or_result_unknown"
if any(
token in lower_log
for token in (
"优惠券",
"购物红包",
"位置交换",
"互换",
"遮挡",
"误触",
)
):
return "ui_position_swap_or_overlay"
if any(
token in lower_log
for token in (
"未找到福袋",
"漏检",
"疑似有福袋",
)
):
return "miss_or_not_found"
if any(
token in lower_log
for token in (
"detail_open_verdict",
"detail_not_recognized",
"detail_data_verdict",
"详情",
"阶段",
)
):
return "detail_stage_anomaly"
if any(
token in lower_log
for token in (
"参与",
"开奖结果",
"未知",
)
):
return "attend_or_result_unknown"
return None
def _promote_long_term_samples(
*,
root: Path,
run_id: str,
copied_debug_images: list[str],
out_dir: Path,
max_per_category: int,
) -> dict[str, Any]:
sample_root = root / "artifacts" / "fudai_regression_samples"
log_text = _read_recent_log_text(root)
selected: dict[str, list[Path]] = {}
debug_root = out_dir / "debug_captures"
for rel in copied_debug_images:
src = debug_root / rel
if not src.exists():
continue
category = _classify_long_term_sample(src, log_text)
if not category:
continue
bucket = selected.setdefault(category, [])
if len(bucket) < max(1, int(max_per_category or 1)):
bucket.append(src)
promoted: list[dict[str, str]] = []
for category, paths in selected.items():
category_dir = sample_root / category
category_dir.mkdir(parents=True, exist_ok=True)
for src in paths:
dst_name = f"{run_id}_{_safe_name(src.stem)}{src.suffix.lower()}"
dst = category_dir / dst_name
if not _copy_file(src, dst):
continue
rel_dst = dst.relative_to(sample_root)
item = {
"run_id": run_id,
"category": category,
"source": str(src.relative_to(out_dir)).replace("\\", "/"),
"sample": str(rel_dst).replace("\\", "/"),
"note": LONG_TERM_SAMPLE_NOTES.get(category, ""),
}
promoted.append(item)
if promoted:
index_path = sample_root / "index.jsonl"
with index_path.open("a", encoding="utf-8") as f:
for item in promoted:
f.write(json.dumps(item, ensure_ascii=False, sort_keys=True) + "\n")
return {
"root": str(sample_root),
"samples": promoted,
"notes": LONG_TERM_SAMPLE_NOTES,
}
def collect_run_regression_artifacts(
*,
run_id: str,
started_at: float,
exit_code: int | None = None,
device_id: str = "",
max_debug_images: int = DEFAULT_MAX_DEBUG_IMAGES,
max_ocr_images: int = DEFAULT_MAX_OCR_IMAGES,
screenshot_tail_lines: int = DEFAULT_SCREENSHOT_CALLS_TAIL_LINES,
max_long_term_samples_per_category: int = DEFAULT_MAX_LONG_TERM_SAMPLES_PER_CATEGORY,
) -> dict[str, Any]:
"""Collect a lightweight-but-rich local regression package after a run exits."""
root = Path(path_config.get_project_root())
safe_run_id = _safe_name(str(run_id or "run"))
out_dir = root / "artifacts" / "fudai_regression_runs" / safe_run_id
out_dir.mkdir(parents=True, exist_ok=True)
copied_logs = _copy_run_logs(
root,
out_dir,
since_ts=float(started_at or 0.0),
screenshot_tail_lines=screenshot_tail_lines,
)
copied_state: list[str] = []
for rel in (
"douyin/core/state/room_pos_map.json",
"douyin/core/state/reservations.json",
"douyin/core/state/room_pos_map.csv",
"douyin/core/state/room_pos_map.md",
):
src = root / rel
dst = out_dir / "state" / Path(rel).name
if _copy_file(src, dst):
copied_state.append(f"state/{dst.name}")
copied_config: list[str] = []
if _copy_file(root / "config" / "config.json", out_dir / "config" / "config.json"):
copied_config.append("config/config.json")
debug_images = _copy_recent_images(
src_root=root / "pic" / "debug_captures",
dst_root=out_dir / "debug_captures",
since_ts=float(started_at or 0.0),
max_images=int(max_debug_images or 0),
)
ocr_images = _copy_recent_images(
src_root=root / "pic" / "ocr",
dst_root=out_dir / "ocr",
since_ts=float(started_at or 0.0),
max_images=int(max_ocr_images or 0),
)
long_term_samples = _promote_long_term_samples(
root=root,
run_id=safe_run_id,
copied_debug_images=debug_images,
out_dir=out_dir,
max_per_category=max_long_term_samples_per_category,
)
manifest: dict[str, Any] = {
"run_id": safe_run_id,
"created_ts": time.time(),
"started_at": float(started_at or 0.0),
"exit_code": exit_code,
"device_id": str(device_id or ""),
"output_dir": str(out_dir),
"copied": {
"logs": copied_logs,
"state": copied_state,
"config": copied_config,
"debug_images": debug_images,
"ocr_images": ocr_images,
},
"long_term_samples": long_term_samples,
"counts": {
"logs": len(copied_logs),
"state": len(copied_state),
"debug_images": len(debug_images),
"ocr_images": len(ocr_images),
"long_term_samples": len(long_term_samples.get("samples", [])),
},
}
(out_dir / "manifest.json").write_text(
json.dumps(manifest, ensure_ascii=False, indent=2),
encoding="utf-8",
)
return {
"run_id": safe_run_id,
"output_dir": str(out_dir),
"manifest": str(out_dir / "manifest.json"),
"counts": manifest["counts"],
}
def build_run_id(prefix: str = "run_cli") -> str:
pid = os.getpid()
return f"{prefix}_{time.strftime('%Y%m%d_%H%M%S')}_{pid}"
+11
View File
@@ -110,6 +110,17 @@ class TestRunCliParseArgs:
result = parse_args(['--y-pianyi', '100'])
assert result.y_pianyi == 100
def test_regression_collection_args(self):
from bin.run_cli import parse_args
result = parse_args([
'--disable-regression-collection',
'--regression-collection-max-images',
'120',
])
assert result.disable_regression_collection is True
assert result.regression_collection_max_images == 120
class TestRunCliModule:
"""run_cli 模块测试。"""
+175
View File
@@ -0,0 +1,175 @@
from __future__ import annotations
import json
from pathlib import Path
def test_collect_run_regression_artifacts_keeps_logs_state_and_debug_images(tmp_path, monkeypatch):
from douyin.testing.regression_collector import collect_run_regression_artifacts
root = tmp_path
logs = root / "logs"
state = root / "douyin" / "core" / "state"
debug = root / "pic" / "debug_captures" / "2026-06-19"
ocr = root / "pic" / "ocr" / "fudai"
cfg = root / "config"
for path in (logs, state, debug, ocr, cfg):
path.mkdir(parents=True)
(logs / "unified_2026-06-19_120000.log").write_text("open\n参与成功\n", encoding="utf-8")
(logs / "detail_2026-06-19.log").write_text("detail\n", encoding="utf-8")
(logs / "screenshot_calls.jsonl").write_text("a\nb\nc\n", encoding="utf-8")
(state / "room_pos_map.json").write_text('{"1":{"has_fudai":true}}', encoding="utf-8")
(state / "reservations.json").write_text('{"reservations":[]}', encoding="utf-8")
(cfg / "config.json").write_text('{"debug":true}', encoding="utf-8")
for idx, name in enumerate(
[
"20260619_120001_px_fdicon_ok_x123.png",
"20260619_120002_ocr_福袋详情综合标注_detail_regions.png",
"20260619_120003_ocr_开奖结果按钮_postocr.png",
]
):
p = debug / name
p.write_bytes(bytes([idx + 1]) * 10)
(ocr / "福袋倒计时_分钟.png").write_bytes(b"minute")
monkeypatch.setattr(
"douyin.testing.regression_collector.path_config.get_project_root",
lambda: str(root),
)
result = collect_run_regression_artifacts(
run_id="unit_run",
started_at=0.0,
exit_code=0,
device_id="device1",
max_debug_images=10,
)
out = Path(result["output_dir"])
assert (out / "manifest.json").exists()
assert (out / "logs" / "unified_2026-06-19_120000.log").exists()
assert (out / "logs" / "screenshot_calls.tail.jsonl").read_text(encoding="utf-8") == "a\nb\nc\n"
assert (out / "state" / "room_pos_map.json").exists()
assert (out / "config" / "config.json").exists()
assert len(list((out / "debug_captures").rglob("*.png"))) == 3
assert any(p.name == "福袋倒计时_分钟.png" for p in (out / "ocr").rglob("*.png"))
manifest = json.loads((out / "manifest.json").read_text(encoding="utf-8"))
assert manifest["run_id"] == "unit_run"
assert manifest["exit_code"] == 0
assert manifest["counts"]["debug_images"] == 3
def test_collect_run_regression_artifacts_limits_debug_images(tmp_path, monkeypatch):
from douyin.testing.regression_collector import collect_run_regression_artifacts
root = tmp_path
debug = root / "pic" / "debug_captures" / "2026-06-19"
debug.mkdir(parents=True)
for idx in range(5):
p = debug / f"20260619_12000{idx}_px_pxstage_ov_ok_1.png"
p.write_bytes(bytes([idx]) * 5)
monkeypatch.setattr(
"douyin.testing.regression_collector.path_config.get_project_root",
lambda: str(root),
)
result = collect_run_regression_artifacts(
run_id="limited",
started_at=0.0,
max_debug_images=2,
)
out = Path(result["output_dir"])
copied = sorted(p.name for p in (out / "debug_captures").rglob("*.png"))
assert len(copied) == 2
assert copied == [
"20260619_120003_px_pxstage_ov_ok_1.png",
"20260619_120004_px_pxstage_ov_ok_1.png",
]
def test_collect_run_regression_artifacts_keeps_only_run_window_logs(tmp_path, monkeypatch):
from douyin.testing.regression_collector import collect_run_regression_artifacts
root = tmp_path
logs = root / "logs"
logs.mkdir(parents=True)
old_log = logs / "unified_2026-06-18.log"
current_log = logs / "unified_2026-06-19.log"
old_log.write_text("old\n", encoding="utf-8")
current_log.write_text("current\n", encoding="utf-8")
old_ts = 100.0
current_ts = 300.0
old_log.touch()
current_log.touch()
import os
os.utime(old_log, (old_ts, old_ts))
os.utime(current_log, (current_ts, current_ts))
monkeypatch.setattr(
"douyin.testing.regression_collector.path_config.get_project_root",
lambda: str(root),
)
result = collect_run_regression_artifacts(run_id="log_window", started_at=200.0)
out = Path(result["output_dir"])
assert not (out / "logs" / old_log.name).exists()
assert (out / "logs" / current_log.name).exists()
def test_collect_run_regression_artifacts_promotes_long_term_error_samples(tmp_path, monkeypatch):
from douyin.testing.regression_collector import collect_run_regression_artifacts
root = tmp_path
logs = root / "logs"
debug = root / "pic" / "debug_captures" / "2026-06-19"
logs.mkdir(parents=True)
debug.mkdir(parents=True)
(logs / "unified_2026-06-19.log").write_text(
"\n".join(
[
"[FDICON] 点击后进入优惠券,可能是福袋 icon 与优惠券入口位置交换",
"[DETAIL_OPEN_VERDICT] detail_not_recognized",
"未找到福袋图标,但当前画面疑似有福袋",
]
),
encoding="utf-8",
)
for name in [
"20260619_px_fdicon_false_left_coupon_x162.png",
"20260619_px_pxstage_miss_no_fudai.png",
"20260619_detail_DETAIL_OPEN_VERDICT_detail_not_recognized.png",
"20260619_px_fdicon_ok_normal.png",
]:
(debug / name).write_bytes(name.encode("utf-8"))
monkeypatch.setattr(
"douyin.testing.regression_collector.path_config.get_project_root",
lambda: str(root),
)
result = collect_run_regression_artifacts(
run_id="sample_pool",
started_at=0.0,
max_debug_images=10,
max_long_term_samples_per_category=2,
)
out = Path(result["output_dir"])
manifest = json.loads((out / "manifest.json").read_text(encoding="utf-8"))
categories = {item["category"] for item in manifest["long_term_samples"]["samples"]}
assert "ui_position_swap_or_overlay" in categories
assert "miss_or_not_found" in categories
assert "detail_stage_anomaly" in categories
assert manifest["long_term_samples"]["notes"]["ui_position_swap_or_overlay"].startswith(
"可能是 UI 位置交换"
)
sample_root = root / "artifacts" / "fudai_regression_samples"
assert (sample_root / "index.jsonl").exists()
assert len(list(sample_root.rglob("*.png"))) >= 3