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() 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", "confirm_failed", ) ): 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" return None def _promote_long_term_samples( *, root: Path, run_id: str, source_images: list[Path], source_base: Path, max_per_category: int, ) -> dict[str, Any]: sample_root = root / "artifacts" / "fudai_regression_samples" selected: dict[str, list[Path]] = {} for src in source_images: if not src.exists(): continue category = _classify_long_term_sample(src, "") 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) try: source_rel = src.relative_to(source_base) except Exception: source_rel = Path(src.name) item = { "run_id": run_id, "category": category, "source": str(source_rel).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, full_run_package: bool = True, ) -> 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 debug_source_root = root / "pic" / "debug_captures" debug_source_images = _iter_recent_files( debug_source_root, since_ts=float(started_at or 0.0), suffixes=(".png", ".jpg", ".jpeg"), ) if max_debug_images > 0 and len(debug_source_images) > max_debug_images: debug_source_images = debug_source_images[-int(max_debug_images):] copied_logs: list[str] = [] copied_state: list[str] = [] copied_config: list[str] = [] debug_images: list[str] = [] ocr_images: list[str] = [] if full_run_package: 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, ) 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}") if _copy_file(root / "config" / "config.json", out_dir / "config" / "config.json"): copied_config.append("config/config.json") for src in debug_source_images: try: rel = src.relative_to(debug_source_root) except Exception: rel = Path(src.name) dst = out_dir / "debug_captures" / rel if _copy_file(src, dst): debug_images.append(str(rel).replace("\\", "/")) 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, source_images=debug_source_images, source_base=debug_source_root, 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 ""), "full_run_package": bool(full_run_package), "output_dir": str(out_dir) if full_run_package else "", "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", [])), }, } manifest_path = "" if full_run_package: manifest_path = str(out_dir / "manifest.json") (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) if full_run_package else "", "manifest": manifest_path, "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}"