feat: Refactor and reorganize project structure with new modules and files
- Deleted obsolete files including test scripts and configuration files to streamline the project. - Introduced new modules for handling Douyin functionalities, including core operations, logging, and GUI components. - Updated import paths to reflect the new module structure, enhancing code organization and maintainability. - Added configuration files and documentation to support the new structure and improve user guidance.
This commit is contained in:
1 parent
ea7159355b
commit
c67f22f76f
139 files changed
+7571
-7828
No files matched your search
@@ -0,0 +1,7 @@
|
||||
"""
|
||||
工具函数模块
|
||||
"""
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
"""
|
||||
配置管理模块
|
||||
============
|
||||
|
||||
负责从 config.json 加载配置并设置到 analyser 对象
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from typing import Any, Optional
|
||||
|
||||
|
||||
class ConfigManager:
|
||||
"""配置管理器类"""
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def load_config_from_file(
|
||||
analyser: Any, config_path: Optional[str] = None
|
||||
) -> None:
|
||||
"""从配置文件加载配置并设置到 analyser 对象
|
||||
|
||||
参数:
|
||||
analyser: fudai_analyse 实例
|
||||
config_path: 配置文件路径,如果为 None 则使用 analyser.config_path
|
||||
"""
|
||||
if config_path is None:
|
||||
config_path = getattr(analyser, "config_path", "config/config.json")
|
||||
|
||||
# 如果 config_path 仍然为 None,直接返回(使用默认值)
|
||||
if config_path is None:
|
||||
return
|
||||
|
||||
# 如果配置文件不存在,直接返回(使用默认值)
|
||||
if not os.path.exists(config_path):
|
||||
return
|
||||
|
||||
try:
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
config = json.load(f)
|
||||
except (json.JSONDecodeError, IOError, OSError):
|
||||
# 如果 JSON 解析失败或文件读取失败,直接返回(使用默认值)
|
||||
return
|
||||
|
||||
# 保存 needswitch 的原始值(如果已通过命令行设置,则保留)
|
||||
original_needswitch = getattr(analyser, "needswitch", None)
|
||||
|
||||
# 加载基本配置
|
||||
if "min_prize_value_yuan" in config:
|
||||
analyser.min_prize_value_yuan = float(config["min_prize_value_yuan"] or 0.0)
|
||||
|
||||
if "min_participants" in config:
|
||||
analyser.min_participants = int(config["min_participants"] or 0)
|
||||
|
||||
if "max_participants" in config:
|
||||
analyser.max_participants = int(config["max_participants"] or 0)
|
||||
|
||||
if "skip_if_countdown_gt_seconds" in config:
|
||||
analyser.skip_if_countdown_gt_seconds = int(
|
||||
config["skip_if_countdown_gt_seconds"] or 900
|
||||
)
|
||||
|
||||
if "skip_if_countdown_lt_seconds" in config:
|
||||
analyser.skip_if_countdown_lt_seconds = int(
|
||||
config["skip_if_countdown_lt_seconds"] or 0
|
||||
)
|
||||
|
||||
if "fudai_icon_max_wait_seconds" in config:
|
||||
analyser.fudai_icon_max_wait_seconds = float(
|
||||
config["fudai_icon_max_wait_seconds"] or 5.0
|
||||
)
|
||||
|
||||
if "fudai_icon_retry_delay_seconds" in config:
|
||||
analyser.fudai_icon_retry_delay_seconds = float(
|
||||
config["fudai_icon_retry_delay_seconds"] or 0.6
|
||||
)
|
||||
|
||||
# 高价值福袋配置
|
||||
if "high_value_fudai_enabled" in config:
|
||||
analyser.high_value_fudai_enabled = bool(
|
||||
config["high_value_fudai_enabled"]
|
||||
)
|
||||
|
||||
if "high_value_fudai_threshold_yuan" in config:
|
||||
analyser.high_value_fudai_threshold_yuan = float(
|
||||
config["high_value_fudai_threshold_yuan"] or 500.0
|
||||
)
|
||||
|
||||
if "high_value_fudai_max_reservations" in config:
|
||||
max_reservations = int(config["high_value_fudai_max_reservations"] or 3)
|
||||
# 限制最大预约数量为50
|
||||
analyser.high_value_fudai_max_reservations = min(max_reservations, 50)
|
||||
|
||||
# needswitch 配置(如果已通过命令行设置,则保留原值)
|
||||
if original_needswitch is not None:
|
||||
# 保留命令行参数值(优先级最高)
|
||||
analyser.needswitch = original_needswitch
|
||||
elif "needswitch" in config:
|
||||
# 从配置文件读取
|
||||
analyser.needswitch = bool(config["needswitch"])
|
||||
else:
|
||||
# 如果配置文件中没有,使用默认值 True
|
||||
analyser.needswitch = True
|
||||
|
||||
# 列表配置
|
||||
if "contains_not_want" in config:
|
||||
analyser.contains_not_want = list(config["contains_not_want"] or [])
|
||||
|
||||
if "contains_want" in config:
|
||||
analyser.contains_want = list(config["contains_want"] or [])
|
||||
|
||||
# 阈值配置(限制在 0.0~1.0 范围内)
|
||||
if "lucky_draw_red_ratio_threshold" in config:
|
||||
threshold = float(config["lucky_draw_red_ratio_threshold"] or 0.9)
|
||||
analyser.lucky_draw_red_ratio_threshold = max(0.0, min(1.0, threshold))
|
||||
|
||||
if "coupon_template_match_threshold" in config:
|
||||
threshold = float(config["coupon_template_match_threshold"] or 0.75)
|
||||
analyser.coupon_template_match_threshold = max(0.0, min(1.0, threshold))
|
||||
|
||||
if "attend_button_red_ratio_threshold" in config:
|
||||
threshold = float(config["attend_button_red_ratio_threshold"] or 0.25)
|
||||
analyser.attend_button_red_ratio_threshold = max(0.0, min(1.0, threshold))
|
||||
|
||||
if "fansclub_join_red_ratio_threshold" in config:
|
||||
threshold = float(config["fansclub_join_red_ratio_threshold"] or 0.25)
|
||||
analyser.fansclub_join_red_ratio_threshold = max(0.0, min(1.0, threshold))
|
||||
|
||||
# 其他配置项(根据实际需要添加)
|
||||
if "no_attend_timeout_minutes" in config:
|
||||
analyser._no_attend_timeout_minutes = float(
|
||||
config["no_attend_timeout_minutes"] or 30.0
|
||||
)
|
||||
|
||||
if "auto_join_fansclub" in config:
|
||||
analyser.auto_join_fansclub = bool(config["auto_join_fansclub"])
|
||||
|
||||
if "fansclub_fail_action" in config:
|
||||
analyser.fansclub_fail_action = str(config["fansclub_fail_action"] or "stay")
|
||||
|
||||
if "high_value_fudai_join_ahead_seconds" in config:
|
||||
analyser.high_value_fudai_join_ahead_seconds = int(
|
||||
config["high_value_fudai_join_ahead_seconds"] or 120
|
||||
)
|
||||
|
||||
if "high_value_fudai_max_swipe_back" in config:
|
||||
analyser.high_value_fudai_max_swipe_back = int(
|
||||
config["high_value_fudai_max_swipe_back"] or 35
|
||||
)
|
||||
|
||||
if "high_value_fudai_after_action" in config:
|
||||
analyser.high_value_fudai_after_action = str(
|
||||
config["high_value_fudai_after_action"] or "continue"
|
||||
)
|
||||
|
||||
if "high_value_fudai_after_stay_seconds" in config:
|
||||
analyser.high_value_fudai_after_stay_seconds = int(
|
||||
config["high_value_fudai_after_stay_seconds"] or 120
|
||||
)
|
||||
|
||||
if "reservation_back_verify_enabled" in config:
|
||||
analyser.reservation_back_verify_enabled = bool(
|
||||
config["reservation_back_verify_enabled"]
|
||||
)
|
||||
|
||||
if "reservation_back_swipe_delay" in config:
|
||||
analyser.reservation_back_swipe_delay = float(
|
||||
config["reservation_back_swipe_delay"] or 0.6
|
||||
)
|
||||
|
||||
if "reservation_preempt_min_value_yuan" in config:
|
||||
analyser.reservation_preempt_min_value_yuan = float(
|
||||
config["reservation_preempt_min_value_yuan"] or 0.0
|
||||
)
|
||||
|
||||
if "poll_before_open_seconds" in config:
|
||||
analyser.poll_before_open_seconds = int(
|
||||
config["poll_before_open_seconds"] or 10
|
||||
)
|
||||
|
||||
if "reset_after_swipes_enabled" in config:
|
||||
analyser.reset_after_swipes_enabled = bool(
|
||||
config["reset_after_swipes_enabled"]
|
||||
)
|
||||
|
||||
if "reset_after_swipes" in config:
|
||||
analyser.reset_after_swipes = int(config["reset_after_swipes"] or 10)
|
||||
|
||||
if "fudai_click_wait_seconds" in config:
|
||||
analyser.fudai_click_wait_seconds = float(
|
||||
config["fudai_click_wait_seconds"] or 2.0
|
||||
)
|
||||
|
||||
if "switch_room_wait_after_stage_diag_seconds" in config:
|
||||
analyser.switch_room_wait_after_stage_diag_seconds = float(
|
||||
config["switch_room_wait_after_stage_diag_seconds"] or 7.0
|
||||
)
|
||||
|
||||
if "swipe_duration_ms" in config:
|
||||
analyser.swipe_duration_ms = int(config["swipe_duration_ms"] or 600)
|
||||
|
||||
if "fudai_finder_optimized_enabled" in config:
|
||||
analyser.fudai_finder_optimized_enabled = bool(
|
||||
config["fudai_finder_optimized_enabled"]
|
||||
)
|
||||
|
||||
if "fudai_click_verify_enabled" in config:
|
||||
analyser.fudai_click_verify_enabled = bool(
|
||||
config["fudai_click_verify_enabled"]
|
||||
)
|
||||
|
||||
if "fudai_find_max_retries" in config:
|
||||
analyser.fudai_find_max_retries = int(config["fudai_find_max_retries"] or 3)
|
||||
|
||||
if "screenshot_diagnose_min_interval_seconds" in config:
|
||||
analyser.screenshot_diagnose_min_interval_seconds = float(
|
||||
config["screenshot_diagnose_min_interval_seconds"] or 8.0
|
||||
)
|
||||
|
||||
if "live_room_match_threshold" in config:
|
||||
threshold = float(config["live_room_match_threshold"] or 0.8)
|
||||
analyser.live_room_match_threshold = max(0.0, min(1.0, threshold))
|
||||
|
||||
if "fudai_template_match_enabled" in config:
|
||||
analyser.fudai_template_match_enabled = bool(
|
||||
config["fudai_template_match_enabled"]
|
||||
)
|
||||
|
||||
if "fudai_template_match_threshold" in config:
|
||||
threshold = float(config["fudai_template_match_threshold"] or 0.7)
|
||||
analyser.fudai_template_match_threshold = max(0.0, min(1.0, threshold))
|
||||
|
||||
if "y_pianyi" in config:
|
||||
analyser.y_pianyi = int(config["y_pianyi"] or 0)
|
||||
@@ -0,0 +1,299 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""
|
||||
工具方法模块
|
||||
============
|
||||
|
||||
职责:通用工具方法
|
||||
- 点击操作封装
|
||||
- OCR检查开奖结果
|
||||
- 处理开奖结果
|
||||
- 截图并诊断
|
||||
- 读取像素阶段状态
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
import shutil
|
||||
from typing import Any, Optional, Tuple, Dict, Union
|
||||
from datetime import datetime
|
||||
|
||||
from douyin.detection import douyin_pixel
|
||||
from douyin.handlers import douyin_screenshot_handler
|
||||
|
||||
|
||||
class HelperFunctions:
|
||||
"""工具函数集合:通用工具方法"""
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def click(analyser: Any, x: int, y: int) -> None:
|
||||
"""兼容原版 fudai_analyse.click:转发到底层 operation.click。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
x: X坐标
|
||||
y: Y坐标
|
||||
"""
|
||||
start_time = time.time()
|
||||
try:
|
||||
analyser.operation.click(analyser.device_id, int(x), int(y))
|
||||
elapsed = time.time() - start_time
|
||||
if elapsed > 0.1: # 只记录耗时较长的点击操作
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"操作",
|
||||
"点击操作",
|
||||
x=int(x),
|
||||
y=int(y),
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def read_pixel_stage_state(
|
||||
analyser: Any, return_details: bool = False
|
||||
) -> Union[Dict[str, Any], Tuple[Dict[str, Any], Dict[str, Any]]]:
|
||||
"""读取像素阶段状态(用于阶段诊断)。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
return_details: 是否返回每个检测步骤的详细信息(包括分数)
|
||||
|
||||
返回:
|
||||
dict: 检测结果(return_details=False时)
|
||||
tuple[dict, dict]: (检测结果, 详细信息)(return_details=True时)
|
||||
"""
|
||||
pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
|
||||
# 获取分辨率比例和y偏移参数
|
||||
resolution_ratio_x = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
resolution_ratio_y = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0)
|
||||
lucky_threshold = float(
|
||||
getattr(analyser, "lucky_draw_red_ratio_threshold", 0.9) or 0.9
|
||||
)
|
||||
# 获取模板匹配阈值(优先使用福袋详情页专用阈值)
|
||||
fudai_template_threshold = float(
|
||||
getattr(analyser, "fudai_detail_template_threshold", None)
|
||||
or getattr(analyser, "fudai_template_match_threshold", 0.7)
|
||||
or 0.7
|
||||
)
|
||||
if fudai_template_threshold < 0.0:
|
||||
fudai_template_threshold = 0.0
|
||||
if fudai_template_threshold > 1.0:
|
||||
fudai_template_threshold = 1.0
|
||||
return douyin_pixel.read_pixel_stage_state_from_screenshot(
|
||||
pic_path,
|
||||
resolution_ratio_x,
|
||||
resolution_ratio_y,
|
||||
y_pianyi,
|
||||
lucky_threshold,
|
||||
fudai_template_threshold,
|
||||
return_details=return_details,
|
||||
analyser=analyser,
|
||||
)
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def check_lottery_result_by_ocr(analyser: Any) -> Optional[str]:
|
||||
"""通过OCR识别开奖结果按钮区域,返回识别到的文本类型。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
|
||||
返回:
|
||||
"我知道了" - 识别到"我知道了"按钮
|
||||
"立即领取奖品" - 识别到"立即领取奖品"按钮
|
||||
None - 未识别到相关文本
|
||||
"""
|
||||
try:
|
||||
# OCR区域:(175, 1267) 到 (890, 1377)
|
||||
# 裁剪区域用于OCR识别(通过cut_pic会自动保存到debug_captures)
|
||||
douyin_screenshot_handler.ScreenshotHandler.cut_pic(
|
||||
analyser, 175, 1267, 890, 1377, "", "开奖结果按钮", 0
|
||||
)
|
||||
|
||||
# OCR识别
|
||||
ocr_text = str(analyser.operation.analyse_pic_word("开奖结果按钮", 0) or "")
|
||||
|
||||
analyser._log_kv("开奖结果", "OCR识别结果", text=ocr_text) # type: ignore[attr-defined]
|
||||
|
||||
# 检查识别到的文本
|
||||
if "我知道了" in ocr_text:
|
||||
return "我知道了"
|
||||
elif (
|
||||
"立即领取奖品" in ocr_text
|
||||
or "领取奖品" in ocr_text
|
||||
or "立即领取" in ocr_text
|
||||
):
|
||||
return "立即领取奖品"
|
||||
else:
|
||||
# 尝试模式1识别
|
||||
ocr_text_1 = str(
|
||||
analyser.operation.analyse_pic_word("开奖结果按钮", 1) or ""
|
||||
)
|
||||
if "我知道了" in ocr_text_1:
|
||||
return "我知道了"
|
||||
elif (
|
||||
"立即领取奖品" in ocr_text_1
|
||||
or "领取奖品" in ocr_text_1
|
||||
or "立即领取" in ocr_text_1
|
||||
):
|
||||
return "立即领取奖品"
|
||||
|
||||
return None
|
||||
except Exception as e:
|
||||
analyser._log_kv("开奖结果", "OCR识别异常", error=str(e)) # type: ignore[attr-defined]
|
||||
return None
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def handle_lottery_result_by_ocr(analyser: Any, result_type: str) -> None:
|
||||
"""根据OCR识别结果处理开奖结果。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
result_type: "我知道了" 或 "立即领取奖品"
|
||||
"""
|
||||
start_time = time.time()
|
||||
try:
|
||||
if result_type == "我知道了":
|
||||
# 识别到"我知道了",点击按钮,切换下一个直播间
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
# 按钮位置在OCR区域中心附近 (175+890)/2=532, (1267+1377)/2=1322
|
||||
btn_x = int(532 * rx // 1080)
|
||||
btn_y = int(1322 * ry // 2400)
|
||||
|
||||
analyser.operation.click(analyser.device_id, btn_x, btn_y)
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"开奖结果", "点击我知道了按钮", x=btn_x, y=btn_y
|
||||
)
|
||||
analyser.operation.delay(0.5)
|
||||
|
||||
# 切换下一个直播间
|
||||
try:
|
||||
needswitch = bool(getattr(analyser, "needswitch", True))
|
||||
except Exception:
|
||||
needswitch = True
|
||||
|
||||
if needswitch:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"开奖结果", "处理完开奖结果,切换直播间找新福袋"
|
||||
)
|
||||
analyser.swipe_up_to_next_live() # type: ignore[attr-defined]
|
||||
else:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"开奖结果",
|
||||
"处理完开奖结果,未启用切换,继续在当前直播间",
|
||||
)
|
||||
|
||||
elif result_type == "立即领取奖品":
|
||||
# 识别到"立即领取奖品",保存全屏截图到单独文件夹,点击返回键,切换下一个直播间
|
||||
try:
|
||||
# 确保有最新截图
|
||||
analyser.operation.get_screenshot(analyser.device_id)
|
||||
|
||||
base_dir = os.path.dirname(__file__)
|
||||
pic_dir = os.path.join(base_dir, "pic")
|
||||
src = os.path.join(pic_dir, "screenshot.png")
|
||||
|
||||
if os.path.exists(src):
|
||||
# 创建单独的文件夹保存"立即领取奖品"的截图
|
||||
prize_dir = os.path.join(pic_dir, "lottery_prize_captures")
|
||||
os.makedirs(prize_dir, exist_ok=True)
|
||||
|
||||
# 保存截图,文件名包含时间戳
|
||||
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
dst = os.path.join(prize_dir, f"prize_{timestamp}.png")
|
||||
shutil.copy(src, dst)
|
||||
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"开奖结果", "已保存立即领取奖品截图", path=dst
|
||||
)
|
||||
except Exception as e:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"开奖结果", "保存截图失败", error=str(e)
|
||||
)
|
||||
|
||||
# 点击返回键
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"开奖结果", "点击返回键关闭开奖结果"
|
||||
)
|
||||
analyser.operation.delay(0.5)
|
||||
|
||||
# 切换下一个直播间
|
||||
try:
|
||||
needswitch = bool(getattr(analyser, "needswitch", True))
|
||||
except Exception:
|
||||
needswitch = True
|
||||
|
||||
if needswitch:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"开奖结果", "处理完开奖结果,切换直播间找新福袋"
|
||||
)
|
||||
analyser.swipe_up_to_next_live() # type: ignore[attr-defined]
|
||||
else:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"开奖结果",
|
||||
"处理完开奖结果,未启用切换,继续在当前直播间",
|
||||
)
|
||||
except Exception as e:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"开奖结果",
|
||||
"处理开奖结果失败",
|
||||
error=str(e),
|
||||
result_type=result_type,
|
||||
)
|
||||
# 失败时尝试按返回键并切换
|
||||
try:
|
||||
analyser.operation.click_back(analyser.device_id)
|
||||
analyser.operation.delay(0.5)
|
||||
analyser.swipe_up_to_next_live() # type: ignore[attr-defined]
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
elapsed = time.time() - start_time
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"流程",
|
||||
"_handle_lottery_result_by_ocr完成",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
result_type=result_type,
|
||||
)
|
||||
|
||||
@staticmethod # type: ignore[misc]
|
||||
def shot_and_diagnose(
|
||||
analyser: Any, tag: str, msg: str, device_id: str, diagnose: bool = True
|
||||
) -> None:
|
||||
"""截图并执行阶段诊断(兼容旧版调用方式)。
|
||||
|
||||
参数:
|
||||
analyser: 分析器对象
|
||||
tag: 日志标签
|
||||
msg: 日志消息
|
||||
device_id: 设备ID
|
||||
diagnose: 是否执行阶段诊断(默认True)
|
||||
"""
|
||||
try:
|
||||
# 截图
|
||||
ok = analyser.operation.get_screenshot(device_id)
|
||||
if not ok:
|
||||
analyser._log_kv(tag, f"{msg} - 获取截图失败", ok=0) # type: ignore[attr-defined]
|
||||
return
|
||||
|
||||
# 如果启用诊断,执行阶段诊断
|
||||
if diagnose:
|
||||
stage, seen = analyser._diagnose_stage_from_current_screen() # type: ignore[attr-defined]
|
||||
analyser._last_diag_stage = stage # type: ignore[attr-defined]
|
||||
analyser._last_diag_seen = seen # type: ignore[attr-defined]
|
||||
analyser._last_diag_ts = time.time() # type: ignore[attr-defined]
|
||||
# 使用位置参数调用,避免与关键字参数冲突
|
||||
analyser._log_kv(tag, msg, **{"stage": stage, "seen": seen}) # type: ignore[attr-defined]
|
||||
else:
|
||||
analyser._log_kv(tag, msg) # type: ignore[attr-defined]
|
||||
except Exception as e:
|
||||
# 避免异常影响主流程
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
tag, f"{msg} - 异常: {type(e).__name__}"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,153 @@
|
||||
"""福袋相关文本解析辅助函数。
|
||||
|
||||
本模块提供若干轻量级的解析函数,主要用于:
|
||||
- 从 OCR 文本中抽取福袋内容/倒计时/价值/参与人数
|
||||
- 方便在单元测试中独立验证文本处理逻辑
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
import re
|
||||
|
||||
from douyin.utils.douyin_utils import normalize_countdown_text, extract_prize_value_yuan
|
||||
|
||||
|
||||
def _safe_str(text: Optional[str]) -> str:
|
||||
"""将输入安全地转换为字符串,None -> 空字符串。"""
|
||||
if text is None:
|
||||
return ""
|
||||
return str(text)
|
||||
|
||||
|
||||
def extract_fudai_content(text: Optional[str]) -> str:
|
||||
"""从 OCR 文本中提取“福袋内容”相关描述。
|
||||
|
||||
当前实现比较宽松:
|
||||
- 优先截取 “福袋内容:xxx” 或 “内容:xxx” 之后的部分
|
||||
- 否则返回原始文本(去掉首尾空白)
|
||||
"""
|
||||
t = _safe_str(text).strip()
|
||||
if not t:
|
||||
return ""
|
||||
|
||||
# 常见前缀:福袋内容:xxx / 奖品内容:xxx / 内容:xxx
|
||||
m = re.search(r"(福袋内容|奖品内容|内容)[::]\s*(.+)", t)
|
||||
if m:
|
||||
return m.group(2).strip()
|
||||
|
||||
# 如果包含“福袋”关键字,简单返回整句,后续需要时可再细化
|
||||
if "福袋" in t:
|
||||
return t
|
||||
|
||||
return t
|
||||
|
||||
|
||||
def extract_fudai_countdown(text: Optional[str]) -> str:
|
||||
"""从 OCR 文本中提取倒计时字符串。
|
||||
|
||||
返回值示例:
|
||||
- ``"05:30"`` / ``"05:30后开奖"``
|
||||
- 若无法解析则返回空字符串。
|
||||
"""
|
||||
t = _safe_str(text)
|
||||
if not t:
|
||||
return ""
|
||||
|
||||
norm = normalize_countdown_text(t)
|
||||
return norm or ""
|
||||
|
||||
|
||||
def extract_fudai_value(text: Optional[str]) -> float:
|
||||
"""从 OCR 文本中提取福袋价值金额(元)。
|
||||
|
||||
直接复用 ``douyin_utils.extract_prize_value_yuan``。
|
||||
"""
|
||||
return float(extract_prize_value_yuan(_safe_str(text)))
|
||||
|
||||
|
||||
def extract_participants_count(text: Optional[str]) -> int:
|
||||
"""从 OCR 文本中提取“参与人数”。
|
||||
|
||||
支持的常见格式示例:
|
||||
- ``"共1份1173人已参与"``
|
||||
- ``"已有1000人参与"``
|
||||
- ``"1173人已参与"``
|
||||
- 若无法解析则返回 0。
|
||||
"""
|
||||
t = _safe_str(text)
|
||||
if not t:
|
||||
return 0
|
||||
|
||||
# 优先匹配“xxxx人已参与 / xxxx人参与 / xxxx人”
|
||||
m = re.search(r"(\d+)\s*人(?:已参与|参与)?", t)
|
||||
if m:
|
||||
try:
|
||||
return int(m.group(1))
|
||||
except ValueError:
|
||||
return 0
|
||||
|
||||
# 退化:查找所有数字,取中等大小的一个,避免把“份数”等误当成人数
|
||||
nums = [int(n) for n in re.findall(r"\d+", t) if n.isdigit()]
|
||||
if not nums:
|
||||
return 0
|
||||
# 简化策略:返回最大值(通常人数是文本里最大的数字)
|
||||
return max(nums)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
import os
|
||||
import re
|
||||
from typing import Iterable
|
||||
|
||||
|
||||
def normalize_countdown_text(text: str) -> str:
|
||||
"""对福袋倒计时类 OCR 文本做标准化,抽离自 douyin_fudai.py,方便复用与单元测试。"""
|
||||
if not text:
|
||||
return ""
|
||||
t = re.sub(r"\s+", "", str(text))
|
||||
t = t.replace(":", ":")
|
||||
# 常见 OCR 混淆纠正(只做轻量替换,避免影响其它文字)
|
||||
t = t.translate(
|
||||
str.maketrans(
|
||||
{
|
||||
"O": "0",
|
||||
"o": "0",
|
||||
"Q": "0",
|
||||
"D": "0",
|
||||
"I": "1",
|
||||
"l": "1",
|
||||
"|": "1",
|
||||
"!": "1",
|
||||
"S": "5",
|
||||
"s": "5",
|
||||
"B": "8",
|
||||
"G": "6",
|
||||
"Z": "2",
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
# 中文:x分y秒 / y秒
|
||||
m = re.search(r"(\d{1,2})分(\d{1,2})秒", t)
|
||||
if m:
|
||||
mm = int(m.group(1))
|
||||
ss = int(m.group(2))
|
||||
if ss >= 60:
|
||||
mm += ss // 60
|
||||
ss = ss % 60
|
||||
return f"{mm}:{ss:02d}"
|
||||
# 仅分钟:x分钟
|
||||
m = re.search(r"(\d{1,2})分钟", t)
|
||||
if m:
|
||||
mm = int(m.group(1))
|
||||
return f"{mm}:00"
|
||||
m = re.search(r"(\d{1,3})秒", t)
|
||||
if m:
|
||||
ss = int(m.group(1))
|
||||
mm = ss // 60
|
||||
ss = ss % 60
|
||||
return f"{mm}:{ss:02d}"
|
||||
# 标准样式:11:37后开奖 / 11:37后开奖
|
||||
m = re.search(r"(\d{1,2})[::](\d{2}).*后开奖", t)
|
||||
if m:
|
||||
mm = int(m.group(1))
|
||||
ss = int(m.group(2))
|
||||
# 若分秒识别反了(例如 53:08 实际应为 08:53),优先选择 <= 15 分钟的解释
|
||||
# 或者秒数不合法(>=60),也尝试交换
|
||||
total1 = mm * 60 + ss
|
||||
total2 = ss * 60 + mm
|
||||
if (total1 > 900 and total2 <= 900) or (ss >= 60 and mm < 60):
|
||||
mm, ss = ss, mm
|
||||
return f"{mm}:{ss:02d}后开奖"
|
||||
# 识别错序:54后开奖04
|
||||
m = re.search(r"(\d{1,2})后开奖(\d{2})", t)
|
||||
if m:
|
||||
mm = int(m.group(1))
|
||||
ss = int(m.group(2))
|
||||
if (mm * 60 + ss) > 900 and (ss * 60 + mm) <= 900:
|
||||
mm, ss = ss, mm
|
||||
return f"{mm}:{ss:02d}后开奖"
|
||||
# 纯 mm:ss 格式(不带"后开奖"):11:17 / 05:11
|
||||
m = re.search(r"^(\d{1,2})[::](\d{1,2})$", t)
|
||||
if m:
|
||||
mm = int(m.group(1))
|
||||
ss = int(m.group(2))
|
||||
# 检查是否需要交换分秒:
|
||||
# 1. 秒数不合法(>=60)且交换后合法
|
||||
# 2. 总时间>15分钟且交换后<=15分钟
|
||||
total1 = mm * 60 + ss
|
||||
total2 = ss * 60 + mm
|
||||
if (ss >= 60 and mm < 60) or (total1 > 900 and total2 <= 900):
|
||||
mm, ss = ss, mm
|
||||
# 如果秒数仍然>=60,进行进位处理
|
||||
if ss >= 60:
|
||||
mm += ss // 60
|
||||
ss = ss % 60
|
||||
return f"{mm}:{ss:02d}"
|
||||
# 纯数字 1137 / 5404
|
||||
digits = "".join(ch for ch in t if ch.isdigit())
|
||||
if len(digits) == 4:
|
||||
a = int(digits[:2])
|
||||
b = int(digits[2:])
|
||||
|
||||
# 生成两种解释:mm:ss 以及交换后的 mm:ss
|
||||
mm1, ss1 = a, b
|
||||
mm2, ss2 = b, a
|
||||
|
||||
total1 = mm1 * 60 + ss1
|
||||
total2 = mm2 * 60 + ss2
|
||||
|
||||
# 默认相信“从左到右”的顺序:前两位=分,后两位=秒。
|
||||
# 只有在明显异常(>15分钟)或秒数不合法时才交换。
|
||||
if ss1 >= 60 and ss2 < 60:
|
||||
mm, ss = mm2, ss2
|
||||
elif ss2 >= 60 and ss1 < 60:
|
||||
mm, ss = mm1, ss1
|
||||
elif total1 > 900 and total2 <= 900:
|
||||
mm, ss = mm2, ss2
|
||||
elif total2 > 900 and total1 <= 900:
|
||||
mm, ss = mm1, ss1
|
||||
else:
|
||||
mm, ss = mm1, ss1
|
||||
|
||||
return f"{mm}:{ss:02d}"
|
||||
# 3 位数字:934 => 09:34
|
||||
if len(digits) == 3:
|
||||
mm = int(digits[0])
|
||||
ss = int(digits[1:])
|
||||
if ss >= 60:
|
||||
# 尝试 15:09(OCR 丢 0)
|
||||
mm2 = int(digits[:2])
|
||||
ss2 = int(digits[2])
|
||||
if ss2 < 60:
|
||||
return f"{mm2:02d}:{ss2:02d}"
|
||||
mm += ss // 60
|
||||
ss = ss % 60
|
||||
return f"{mm:02d}:{ss:02d}"
|
||||
# 2 位数字:31 => 00:31(更符合临近开奖)
|
||||
if len(digits) == 2:
|
||||
return f"00:{int(digits):02d}"
|
||||
return t
|
||||
|
||||
|
||||
def extract_prize_value_yuan(text: str) -> float:
|
||||
"""从 OCR 文本中抽取奖品价值金额(元),抽离自 douyin_fudai.py。"""
|
||||
if not text:
|
||||
return 0.0
|
||||
t = re.sub(r"\s+", "", str(text))
|
||||
# 先去掉倒计时类数字,避免把 00:31 解析成 31 元
|
||||
t = re.sub(r"\b\d{1,2}[::]\d{2}\b", "", t)
|
||||
|
||||
# 优先匹配带币种符号/单位的金额:参考价值¥199 / ¥199.9 / ¥199 / 199元
|
||||
# 先尝试匹配带¥符号的金额(¥符号可能被OCR识别成各种形式)
|
||||
currency_matches = re.findall(r"[¥¥\u00A5\uFFE5](\d+(?:\.\d+)?)", t)
|
||||
yuan_matches = re.findall(r"(\d+(?:\.\d+)?)元", t)
|
||||
tagged: Iterable[str] = list(currency_matches) + list(yuan_matches)
|
||||
if tagged:
|
||||
vals: list[float] = []
|
||||
for n in tagged:
|
||||
try:
|
||||
vals.append(float(n))
|
||||
except ValueError:
|
||||
pass
|
||||
if vals:
|
||||
return max(vals)
|
||||
|
||||
# 清理¥符号:OCR可能把¥符号识别成数字或其他字符,先清理掉
|
||||
# ¥符号的Unicode编码是 \u00A5,全角¥是 \uFFE5
|
||||
# 使用更精确的匹配:只在数字前清理¥符号
|
||||
t = re.sub(r"[¥¥\u00A5\uFFE5]\s*(\d)", r"\1", t) # 清理¥符号(保留后面的数字)
|
||||
# 处理¥被识别成Y/y的情况:Y/y后跟数字
|
||||
t = re.sub(r"[Yy]\s*(\d)", r"\1", t) # 清理Y/y(保留后面的数字)
|
||||
|
||||
# 注意:不在这里处理¥被识别成8的情况,因为真正的8199元是合理的
|
||||
# 将在后续提取整数时,根据上下文更智能地判断
|
||||
|
||||
# 清理后再次尝试匹配"元"后缀
|
||||
yuan_matches_after_clean = re.findall(r"(\d+(?:\.\d+)?)元", t)
|
||||
if yuan_matches_after_clean:
|
||||
vals_after_clean: list[float] = []
|
||||
for n in yuan_matches_after_clean:
|
||||
try:
|
||||
vals_after_clean.append(float(n))
|
||||
except ValueError:
|
||||
pass
|
||||
if vals_after_clean:
|
||||
return max(vals_after_clean)
|
||||
|
||||
# 去掉常见干扰:份数/参与人数
|
||||
t = re.sub(r"共\d+份", "", t)
|
||||
t = re.sub(r"\d+人已参与", "", t)
|
||||
|
||||
# 退化:抓小数
|
||||
decimals = re.findall(r"\d+\.\d+", t)
|
||||
if decimals:
|
||||
vals = []
|
||||
for n in decimals:
|
||||
try:
|
||||
val = float(n)
|
||||
# 过滤掉明显不合理的值(比如小数点前有多个数字,可能是误识别)
|
||||
if 0.01 <= val <= 99999.99:
|
||||
vals.append(val)
|
||||
except ValueError:
|
||||
pass
|
||||
if vals:
|
||||
return max(vals)
|
||||
|
||||
# 再退化:抓整数
|
||||
ints = re.findall(r"\d+", t)
|
||||
if ints:
|
||||
vals = []
|
||||
for n in ints:
|
||||
try:
|
||||
v = int(n)
|
||||
# 处理¥被识别成8的情况:需要更智能的判断,避免误识别真正的8199元
|
||||
# 只在以下情况才考虑去掉第一个8:
|
||||
# 1. 数字非常大(>=50000),且去掉8后的数字在合理范围内(100-9999)
|
||||
# 2. 文本中没有明确的单位(如"元"),说明可能是纯数字OCR误识别
|
||||
# 3. 如果数字本身就在合理范围内(1-99999),优先保留原值(可能是真正的8199元)
|
||||
if len(n) >= 5 and n.startswith("8"): # 5位以上数字才考虑
|
||||
corrected = int(n[1:])
|
||||
# 只在原数字非常大(>=50000)且去掉8后数字在合理范围(100-9999)时,才考虑修正
|
||||
# 这样可以避免把真正的8199、81999等误识别
|
||||
if v >= 50000 and 100 <= corrected <= 9999:
|
||||
# 检查文本中是否有"元"等明确单位
|
||||
has_yuan_unit = "元" in t
|
||||
# 如果没有明确单位,更可能是误识别(¥被识别成8)
|
||||
if not has_yuan_unit:
|
||||
vals.append(float(corrected))
|
||||
else:
|
||||
# 有明确单位,保留原值(可能是真正的价值,如81999元)
|
||||
if 1 <= v <= 99999:
|
||||
vals.append(float(v))
|
||||
elif 1 <= v <= 99999:
|
||||
# 数字在合理范围内,保留原值(包括8199、81999等)
|
||||
vals.append(float(v))
|
||||
elif 1 <= v <= 99999:
|
||||
vals.append(float(v))
|
||||
except ValueError:
|
||||
continue
|
||||
if vals:
|
||||
return max(vals)
|
||||
|
||||
return 0.0
|
||||
|
||||
|
||||
def parse_countdown_seconds(text: str) -> int:
|
||||
"""
|
||||
将福袋倒计时文本解析为总秒数。
|
||||
|
||||
这是对 ``normalize_countdown_text`` 的简单封装,方便在其它模块或测试中直接得到秒数。
|
||||
|
||||
示例::
|
||||
|
||||
>>> parse_countdown_seconds("5分30秒")
|
||||
330
|
||||
>>> parse_countdown_seconds("30秒")
|
||||
30
|
||||
>>> parse_countdown_seconds("5:00")
|
||||
300
|
||||
"""
|
||||
norm = normalize_countdown_text(text)
|
||||
if not norm:
|
||||
return 0
|
||||
# 期望格式 "mm:ss" 或 "mm:ss后开奖"
|
||||
m = re.search(r"(\d{1,3}):(\d{1,2})", norm)
|
||||
if not m:
|
||||
return 0
|
||||
try:
|
||||
mm = int(m.group(1))
|
||||
ss = int(m.group(2))
|
||||
except ValueError:
|
||||
return 0
|
||||
return mm * 60 + ss
|
||||
|
||||
|
||||
class Tee:
|
||||
"""将 print 输出同时写入多个文件对象的简单工具类。"""
|
||||
|
||||
def __init__(self, *files):
|
||||
self.files = files
|
||||
|
||||
def write(self, obj):
|
||||
for f in self.files:
|
||||
f.write(obj)
|
||||
f.flush()
|
||||
|
||||
def flush(self):
|
||||
for f in self.files:
|
||||
f.flush()
|
||||
Reference in new issue
Block a user