"""douyin_reservation_handler_pkg.dump_state - 序列化 room_pos_to_title_map。 _dump_room_pos_map_to_state:把 analyser._room_pos_to_title_map 写入 douyin/core/state/room_pos_map.json,供 GUI / 测试查看。 """ from __future__ import annotations import csv import difflib import json import os import time from typing import Any, Dict, Optional from douyin.core import path_config from douyin.fudai import douyin_fudai_detail from douyin.handlers import douyin_swipe_handler from douyin.reservation import douyin_reservation_logic # 错误处理工具占位(与原文件保持兼容降级) try: from douyin.reservation.core.reservation_error_utils import ( log_reservation_error, format_reservation_context, ) _RESERVATION_ERROR_UTILS_AVAILABLE = True except ImportError: def log_reservation_error(*args, **kwargs): return None def format_reservation_context(*args, **kwargs): return {} _RESERVATION_ERROR_UTILS_AVAILABLE = False def _dump_room_pos_map_to_state(analyser: Any) -> None: """将 analyser._room_pos_to_title_map 序列化到 douyin/core/state/room_pos_map.json。 结构为 {"": [title, title_raw], ...},Unicode保持原样。 """ try: room_pos_map = getattr(analyser, "_room_pos_to_title_map", {}) # 即使没有映射,也希望写入本次运行的元信息 state_dir = os.path.join(path_config.PROJECT_ROOT, "douyin", "core", "state") os.makedirs(state_dir, exist_ok=True) final_path = os.path.join(state_dir, "room_pos_map.json") tmp_path = final_path + ".tmp" # 过滤并保留映射: # - 对于 dict 条目(新格式),保留完整 dict(以便包含 fudai_detail 等字段) # - 对于旧格式 list/tuple,保持原有行为(写入 [title, title_raw]) # 条件:如果条目没有标题/原始标题且也不包含福袋信息,则跳过 filtered = {} for k, v in room_pos_map.items(): try: if isinstance(v, dict): title = (v.get("title", "") or "").strip() title_raw = (v.get("title_raw", "") or "").strip() has_fudai = bool(v.get("has_fudai", False)) fudai_detail = v.get("fudai_detail") # 如果既没有标题也没有福袋信息,则跳过 if ( not title and not title_raw and not has_fudai and not fudai_detail ): continue # 保留完整 dict,便于 GUI 读取更多字段 filtered[str(k)] = v else: # 兼容旧格式:仍然写入 [title, title_raw] title = (v[0] or "").strip() if len(v) > 0 else "" title_raw = (v[1] or "").strip() if len(v) > 1 else "" if not title and not title_raw: continue filtered[str(k)] = [title, title_raw] except Exception: # 忽略单条处理错误,继续下一个 continue # 准备写入数据:保留原有 top-level 映射结构,同时添加一个保留的元信息字段 data = dict(filtered) try: data["_meta"] = { "source": final_path, "generated_ts": int(time.time()), "run_id": getattr(analyser, "_run_id", ""), } except Exception: data["_meta"] = {"generated_ts": int(time.time())} # 使用漂亮的缩进写入 JSON(先写 tmp 再替换) with open(tmp_path, "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=2) try: os.replace(tmp_path, final_path) except Exception: # os.replace 在某些环境可能不可用,回退到重命名 os.rename(tmp_path, final_path) # 同步导出 CSV 和 Markdown 表格(仅包含映射条目,不包含 _meta) try: csv_path = os.path.join(state_dir, "room_pos_map.csv") csv_tmp = csv_path + ".tmp" md_path = os.path.join(state_dir, "room_pos_map.md") md_tmp = md_path + ".tmp" # 写 CSV with open(csv_tmp, "w", encoding="utf-8", newline="") as cf: writer = csv.writer(cf) writer.writerow( ["pos", "title", "title_raw", "has_fudai", "fudai_content"] ) for k in sorted( filtered.keys(), key=lambda x: int(x) if x.isdigit() else x ): v = room_pos_map.get(int(k) if k.isdigit() else k, {}) if isinstance(v, dict): title = v.get("title", "") title_raw = v.get("title_raw", "") has_fudai = v.get("has_fudai", False) fudai_content = v.get("fudai_content", "") else: # 兼容旧格式 title = v[0] if len(v) > 0 else "" title_raw = v[1] if len(v) > 1 else "" has_fudai = False fudai_content = "" writer.writerow( [k, title, title_raw, has_fudai, fudai_content[:100]] ) try: os.replace(csv_tmp, csv_path) except Exception: os.rename(csv_tmp, csv_path) # 写 Markdown(顶部注释 source) with open(md_tmp, "w", encoding="utf-8") as mf: mf.write(f"\n\n") mf.write("| 位置 | 标题 | 原始标题 | 有福袋 | 福袋内容 |\n") mf.write("|-:|:-|:-|:-:|:-|\n") for k in sorted( filtered.keys(), key=lambda x: int(x) if x.isdigit() else x ): v = room_pos_map.get(int(k) if k.isdigit() else k, {}) if isinstance(v, dict): title = v.get("title", "").replace("|", "\\|") title_raw = v.get("title_raw", "").replace("|", "\\|") has_fudai = "✓" if v.get("has_fudai", False) else "" fudai_content = ( v.get("fudai_content", "")[:50] + "..." if len(v.get("fudai_content", "")) > 50 else v.get("fudai_content", "") ).replace("|", "\\|") else: # 兼容旧格式 title = (v[0] if len(v) > 0 else "").replace("|", "\\|") title_raw = (v[1] if len(v) > 1 else "").replace("|", "\\|") has_fudai = "" fudai_content = "" mf.write( f"| {k} | {title} | {title_raw} | {has_fudai} | {fudai_content} |\n" ) try: os.replace(md_tmp, md_path) except Exception: os.rename(md_tmp, md_path) except Exception: # 导出 CSV/MD 失败不影响 JSON 写入 try: analyser._log_kv("预约", "[预约] 导出 CSV/MD 失败") except Exception: pass except Exception: try: analyser._log_kv("预约", "[预约] 序列化映射表到文件失败") except Exception: pass