Files
douyi_guaji_main/douyin_high_value_room.py
T
Your Name 8b47b506d6 feat: Enhance 福袋 detection and reservation logic
- Updated `config.json` to introduce new settings for infinite loop mode and adjust various thresholds for 福袋 detection.
- Refined the pixel detection logic in `douyin_detection.py` to improve error handling and retry mechanisms.
- Enhanced reservation handling in `douyin_flow_control.py` to prioritize high-value 福袋 and streamline the switching process.
- Improved the GUI in `gui_app.py` to support new configuration options and ensure better user experience.
- Added new tools for analyzing 福袋 colors and comparing them with coupon colors to aid in detection accuracy.
- Updated documentation to reflect changes in configuration and usage instructions.
2025-12-20 13:32:32 +08:00

248 lines
8.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from __future__ import annotations
"""
高价值直播间记录模块
====================
提供高价值直播间的记录和管理功能:
- 跨运行持久化(写入 high_value_rooms.json)
- 记录最大价值、最后价值、首次/最后记录时间
- 记录次数统计
- 支持别名和合并逻辑
"""
from typing import Any, Dict, Optional
import os
import time
import re
import difflib
from path_config import get_high_value_rooms_path
import douyin_reservation
def _normalize_room_title(t: str) -> str:
"""规范化直播间标题(与 douyin_fudai_detail 中的逻辑一致)。"""
try:
s = str(t or "").strip()
except Exception:
return ""
s = s.replace("\r", " ").replace("\n", " ").strip()
s = re.sub(r"\s+", "", s)
for w in ("点赞", "赞", "关注", "粉丝", "直播中", "正在直播", "进入直播间", "推荐", "在线", "人在线"):
s = s.replace(w, "")
s = re.sub(r"\d+(?:\.\d+)?[万wW]?(?:点赞|赞|关注|粉丝)", "", s)
s = re.sub(r"\d+(?:\.\d+)?[万wW]?本场(?:点赞|点赞|点贊|点)", "", s)
s = re.sub(r"本场(?:点赞|点赞|点贊|点)", "", s)
s = re.sub(r"[^0-9A-Za-z\u4e00-\u9fff]", "", s)
return s
def _resolve_high_value_room_key(
title_norm: str,
title_raw: str,
pos_seen0: Optional[int] = None,
high_value_rooms_map: Optional[Dict[str, Dict[str, Any]]] = None,
) -> tuple[str, str, str, float]:
"""将本次识别结果映射到"历史表"里的 canonical key。
返回:(key, key_kind, merged_from, merged_ratio)
- merged_from:本次候选 key(若发生合并)
- merged_ratio:合并相似度
"""
if not high_value_rooms_map:
high_value_rooms_map = {}
key0 = title_norm
key_kind0 = "norm"
if not key0:
# 退化为使用原始文本
try:
s = str(title_raw or "")
s = s.replace("\r", " ").replace("\n", " ").replace("\t", " ")
s = re.sub(r"\s+", "", s).strip()
if len(s) > 64:
s = s[:64]
key0 = s or "unknown"
except Exception:
key0 = "unknown"
# 尝试在历史表中找到相似度最高的 key
best_key = ""
best_ratio = 0.0
best_pos_ok = False
for k, v in high_value_rooms_map.items():
if not k:
continue
try:
ratio = float(difflib.SequenceMatcher(None, key0, k).ratio())
except Exception:
ratio = 0.0
pos_ok = False
if pos_seen0 is not None:
try:
stored_pos = int(v.get("pos_seen") or 0)
if stored_pos > 0 and abs(stored_pos - pos_seen0) <= 3:
pos_ok = True
except Exception:
pass
if ratio > best_ratio:
best_ratio = ratio
best_key = str(k)
best_pos_ok = bool(pos_ok)
if best_key:
if best_pos_ok and best_ratio >= 0.80:
return best_key, str((high_value_rooms_map.get(best_key) or {}).get("key_kind") or "norm"), key0, float(best_ratio)
if best_ratio >= 0.88:
return best_key, str((high_value_rooms_map.get(best_key) or {}).get("key_kind") or "norm"), key0, float(best_ratio)
return key0, key_kind0, "", 0.0
def touch_high_value_room(
analyser: Any,
title_norm: str,
title_raw: str,
prize_value_yuan: float,
reason: str = "",
increment: bool = True,
key_kind: str = "norm",
content: str = "",
pos_seen: Optional[int] = None,
alias_norm: str = "",
alias_raw: str = "",
merged_from: str = "",
merged_ratio: Optional[float] = None,
) -> None:
"""记录高价值直播间信息。
参数:
analyser: 分析器对象
title_norm: 规范化后的直播间标题
title_raw: 原始直播间标题
prize_value_yuan: 奖品价值(元)
reason: 记录原因
increment: 是否增加计数
key_kind: key 类型
content: 福袋内容
pos_seen: 记录时的位置
alias_norm: 别名(规范化)
alias_raw: 别名(原始)
merged_from: 合并来源
merged_ratio: 合并相似度
"""
try:
# 获取高价值直播间映射
high_value_rooms_path = get_high_value_rooms_path()
high_value_rooms_map = douyin_reservation.load_high_value_rooms_map(high_value_rooms_path)
# 解析 key
key, key_kind_resolved, merged_from_resolved, merged_ratio_resolved = _resolve_high_value_room_key(
title_norm, title_raw, pos_seen, high_value_rooms_map
)
if not key:
return
# 如果发生合并,使用合并后的值
if merged_from_resolved and merged_from_resolved != key:
merged_from = merged_from_resolved
if merged_ratio_resolved > 0:
merged_ratio = merged_ratio_resolved
if key_kind_resolved:
key_kind = key_kind_resolved
now0 = time.time()
ex = high_value_rooms_map.get(key) or {}
def _append_unique_list_field(field: str, val: str, cap: int = 8) -> None:
if not val:
return
try:
arr = ex.get(field)
if not isinstance(arr, list):
arr = []
if val not in arr:
arr.insert(0, val)
if len(arr) > cap:
arr = arr[:cap]
ex[field] = arr
except Exception:
pass
if float(ex.get("first_seen_ts") or 0.0) <= 0:
ex["first_seen_ts"] = now0
ex["last_seen_ts"] = now0
if "seen_count" not in ex:
ex["seen_count"] = 0
if increment:
try:
ex["seen_count"] = int(ex.get("seen_count") or 0) + 1
except Exception:
ex["seen_count"] = 1
if pos_seen is not None:
try:
ex["pos_seen"] = int(pos_seen)
except Exception:
pass
ex["pos_updated_ts"] = now0
if title_raw:
ex["room_title_raw_last"] = str(title_raw)
if alias_raw:
_append_unique_list_field("alias_raw", str(alias_raw), cap=8)
if alias_norm and alias_norm != key:
_append_unique_list_field("alias_norm", str(alias_norm), cap=8)
if merged_from and merged_from != key:
ex["merged_from_last"] = str(merged_from)
if merged_ratio is not None:
try:
ex["merged_ratio_last"] = float(merged_ratio)
except Exception:
pass
if key_kind:
ex["key_kind"] = str(key_kind)
if content:
ex["last_content"] = str(content)
try:
pv = float(prize_value_yuan or 0.0)
except Exception:
pv = 0.0
ex["last_prize_value_yuan"] = pv
try:
ex["max_prize_value_yuan"] = max(float(ex.get("max_prize_value_yuan") or 0.0), pv)
except Exception:
ex["max_prize_value_yuan"] = pv
high_value_rooms_map[key] = ex
# 写入状态文件
douyin_reservation.write_high_value_rooms_state(high_value_rooms_path, high_value_rooms_map, reason=reason)
try:
analyser._log_kv(
"高价值直播间",
"已记录高价值直播间",
room_title=key[:30],
prize_value_yuan=pv,
max_prize_value_yuan=ex.get("max_prize_value_yuan", 0),
seen_count=ex.get("seen_count", 0),
)
except Exception:
pass
except Exception as e:
try:
analyser._log_kv(
"高价值直播间",
"记录高价值直播间失败",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass