diff --git a/douyin/fudai/core/fudai_attend.py b/douyin/fudai/core/fudai_attend.py index 7e720ee..921e2a1 100644 --- a/douyin/fudai/core/fudai_attend.py +++ b/douyin/fudai/core/fudai_attend.py @@ -520,1060 +520,10 @@ def attend_choujiang(analyser) -> bool: elif attend_button_text and ( "加入粉丝团" in attend_button_text or "粉丝团" in attend_button_text ): - # 需要粉丝团门槛:先点击参与按钮,再使用OCR识别"加入粉丝团"按钮位置并点击,最后关闭详情页 - analyser.last_attend_fail_reason = "fansclub_required" - - # 保存debug截图:标注OCR识别区域(参与按钮区域) - try: - from douyin.handlers import douyin_screenshot_manager - - pic_path = path_config.get_screenshot_path() - if os.path.exists(pic_path): - from PIL import Image - - pic = Image.open(pic_path) - pic.load() - pic_rgb = pic.convert("RGB") - width, height = pic_rgb.size - rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) - ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) - # 缩放OCR区域坐标到实际分辨率 - ocr_x1 = int(306 * width / rx) - ocr_y1 = int(2030 * height / ry) - ocr_x2 = int(780 * width / rx) - ocr_y2 = int(2110 * height / ry) - # 保存debug截图 - debug_path = douyin_screenshot_manager.save_debug_image( - pic_rgb, - operation_type="ocr", - picname="参与按钮", - step="识别参与按钮", - coords=(ocr_x1, ocr_y1, ocr_x2, ocr_y2), - extra_info={ - "ocr_text": attend_button_text[:50], - "region": "(306,2030)-(780,2110)", - "result": "需要粉丝团", - }, - ) - except Exception: - pass - - # 第一步:先点击参与按钮(基于OCR区域中心:OCR区域(306,2030)-(780,2110),区域中心(543, 2070)) - analyser.click(543, 2070) - analyser._log_kv( - "参与", - "粉丝团门槛:先点击参与按钮", - result="需要粉丝团", - base_x=543, - base_y=2070, - region="(306,2030)-(780,2110)", + from douyin.fudai.core.fudai_attend_pkg.fansclub_handler import ( + handle_fansclub_branch, ) - analyser.operation.delay(1.0) # 等待参与按钮响应稍长一些,避免过快 - - # 第二步:使用OCR识别"加入粉丝团"按钮位置并点击(使用OCR识别的文字位置) - try: - rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) - ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) - - # OCR识别区域(扩大范围以便更容易识别) - ocr_region_x1, ocr_region_y1, ocr_region_x2, ocr_region_y2 = ( - 150, - 1900, - 950, - 2200, - ) - analyser.cut_pic( - ocr_region_x1, - ocr_region_y1, - ocr_region_x2, - ocr_region_y2, - "", - "加入粉丝团按钮", - ) - - # 获取OCR原始结果(包含bbox信息) - fansclub_text = "" - fansclub_bbox = None - - # 尝试模式0 - try: - # 获取裁剪后的图片路径 - pic_path = analyser.operation._find_pic_path("加入粉丝团按钮") - if pic_path and os.path.exists(pic_path): - from PIL import Image - - img = Image.open(pic_path) - img = img.convert("RGB") - import numpy as np - - img_np = np.array(img) - - # 调用OCR获取原始结果 - if getattr(analyser.operation, "ocr_type", None) == "easyocr": - ocr_result = analyser.operation.ocr.readtext(img_np) - else: - ocr_result = analyser.operation.ocr.ocr(img_np) - if ocr_result == [None]: - ocr_result = [] - - # 从OCR结果中查找"加入粉丝团"或"粉丝团"文字及其bbox - if isinstance(ocr_result, list) and ocr_result: - # PaddleOCR格式:[[[box], (text, score)], ...] - # EasyOCR格式:[(bbox, text, confidence), ...] - items = ( - ocr_result[0] - if ( - isinstance(ocr_result, list) - and len(ocr_result) == 1 - and isinstance(ocr_result[0], list) - ) - else ocr_result - ) - - for item in items: - text = "" - bbox = None - - # 提取文本和bbox - if isinstance(item, (list, tuple)): - if len(item) >= 2: - # EasyOCR格式:[(bbox, text, confidence), ...] - if ( - isinstance(item[0], (list, tuple)) - and len(item[0]) >= 2 - ): - bbox = item[0] # bbox是第一个元素 - if isinstance(item[1], str): - text = item[1] - # PaddleOCR格式:[box, (text, score)] - elif ( - isinstance(item[1], (list, tuple)) - and len(item[1]) >= 1 - ): - bbox = ( - item[0] - if isinstance(item[0], (list, tuple)) - else None - ) - if isinstance(item[1][0], str): - text = item[1][0] - - # 检查是否包含"加入粉丝团"或"粉丝团" - if ( - text - and ("加入粉丝团" in text or "粉丝团" in text) - and bbox - ): - fansclub_text = text - fansclub_bbox = bbox - break - except Exception as e: - analyser._log_kv( - "参与", "获取OCR原始结果失败", error=str(e), level="WARNING" - ) - - # 如果模式0没有找到,尝试模式1(使用analyse_pic_word) - if not fansclub_text: - fansclub_text = str( - analyser.operation.analyse_pic_word("加入粉丝团按钮", 1) or "" - ) - - # 保存debug截图:标注OCR识别区域(加入粉丝团按钮区域) - try: - from douyin.handlers import douyin_screenshot_manager - - pic_path = path_config.get_screenshot_path() - if os.path.exists(pic_path): - from PIL import Image - - pic = Image.open(pic_path) - pic.load() - pic_rgb = pic.convert("RGB") - width, height = pic_rgb.size - # 缩放OCR区域坐标到实际分辨率 - ocr_x1 = int(ocr_region_x1 * width / rx) - ocr_y1 = int(ocr_region_y1 * height / ry) - ocr_x2 = int(ocr_region_x2 * width / rx) - ocr_y2 = int(ocr_region_y2 * height / ry) - # 保存debug截图 - debug_path = douyin_screenshot_manager.save_debug_image( - pic_rgb, - operation_type="ocr", - picname="加入粉丝团按钮", - step="识别加入粉丝团按钮", - coords=(ocr_x1, ocr_y1, ocr_x2, ocr_y2), - extra_info={ - "ocr_text": fansclub_text[:50] if fansclub_text else "", - "region": f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})", - "result": ( - "识别成功" - if fansclub_text - and ( - "加入粉丝团" in fansclub_text - or "粉丝团" in fansclub_text - ) - else "识别失败" - ), - "has_bbox": fansclub_bbox is not None, - }, - ) - except Exception: - pass - - # 如果识别到"加入粉丝团"相关文字,使用OCR识别的文字位置点击 - if fansclub_text and ( - "加入粉丝团" in fansclub_text or "粉丝团" in fansclub_text - ): - click_x = None - click_y = None - - # 如果获取到了bbox,使用bbox的中心位置 - if fansclub_bbox: - try: - # 提取bbox的坐标点 - xs = [] - ys = [] - for p in fansclub_bbox: - if isinstance(p, (list, tuple)) and len(p) >= 2: - xs.append(float(p[0])) - ys.append(float(p[1])) - - if xs and ys: - # 计算bbox中心(在裁剪图片中的坐标) - bbox_center_x = (min(xs) + max(xs)) / 2 - bbox_center_y = (min(ys) + max(ys)) / 2 - - # 将裁剪图片坐标转换为全屏坐标 - # 需要加上OCR区域的偏移 - full_x = ocr_region_x1 + bbox_center_x - full_y = ocr_region_y1 + bbox_center_y - - # 缩放到实际分辨率 - click_x = int(full_x * rx // 1080) - click_y = int(full_y * ry // 2400) - except Exception as e: - analyser._log_kv( - "参与", - "计算bbox中心失败", - error=str(e), - level="WARNING", - ) - - # 如果bbox计算失败,使用OCR区域中心作为备选 - if click_x is None or click_y is None: - click_x = int((ocr_region_x1 + ocr_region_x2) / 2 * rx // 1080) - click_y = int((ocr_region_y1 + ocr_region_y2) / 2 * ry // 2400) - - analyser.operation.click(analyser.device_id, click_x, click_y) - analyser._log_kv( - "参与", - "粉丝团门槛:点击加入粉丝团按钮(OCR识别文字位置)", - ocr_text=fansclub_text[:50], - x=click_x, - y=click_y, - base_x=( - int((ocr_region_x1 + ocr_region_x2) / 2) - if click_x is None - else None - ), - base_y=( - int((ocr_region_y1 + ocr_region_y2) / 2) - if click_y is None - else None - ), - region=f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})", - used_bbox=fansclub_bbox is not None, - ) - else: - # OCR未识别到"加入粉丝团",使用OCR区域中心作为备选 - region_center_x = int( - (ocr_region_x1 + ocr_region_x2) / 2 * rx // 1080 - ) - region_center_y = int( - (ocr_region_y1 + ocr_region_y2) / 2 * ry // 2400 - ) - analyser.operation.click( - analyser.device_id, region_center_x, region_center_y - ) - analyser._log_kv( - "参与", - "粉丝团门槛:点击加入粉丝团按钮(OCR未识别到文字,使用区域中心)", - ocr_text=fansclub_text[:50] if fansclub_text else "", - x=region_center_x, - y=region_center_y, - base_x=(ocr_region_x1 + ocr_region_x2) // 2, - base_y=(ocr_region_y1 + ocr_region_y2) // 2, - region=f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})", - ) - # 等待点击完成(使用可配置延迟) - analyser.operation.delay(getattr(analyser, "fansclub_click_delay", 1.2)) - except Exception as e: - analyser._log_kv("参与", "点击加入粉丝团按钮失败", error=str(e)) - - # 第三步:关闭详情页 - analyser.click(500, 470) # 点击详情页旁边位置关闭详情页 - analyser._log_kv("参与", "关闭福袋详情", action="关闭详情") - - if not analyser.auto_join_fansclub: - analyser._log_kv( - "参与", "未启用自动加粉丝团:等待手动确认", wait_seconds=15 - ) - analyser.operation.delay(15) - - # 点击粉丝团按钮后,可能进入"加入粉丝团"独立页面:需要在该页再次点击"加入粉丝团"才能成功。 - def _recover_to_fudai_detail_after_fansclub(max_steps: int = 4) -> bool: - for i in range(int(max_steps or 4)): - try: - analyser._shot_and_diagnose( - "粉丝团", - "粉丝团后定位福袋详情({}/{})".format(i + 1, max_steps), - analyser.device_id, - ) - except Exception: - pass - try: - # 已在打开详情时完成阶段诊断,后续不再重复调用 - st, seen = "", "" - except Exception: - st, seen = "", "" - - if st == "FUDai_DETAIL": - return True - - if st == "FANSCLUB_JOIN": - # 在加入页点击底部"加入粉丝团"按钮(与详情页按钮同位置) - analyser._log_kv( - "参与", - "粉丝团加入页:点击加入粉丝团", - stage=st, - seen=seen, - attempt=i + 1, - ) - try: - # 点击加入粉丝团按钮 - # 基于实际截图分析:OCR区域 (200, 1940, 880, 2140),尺寸680x200 - # 按钮上部66%是红色区域(文字"加入粉丝团"所在),高度约132像素 - # 红色区域Y范围:1940 到 2072,中心Y = 1940 + 132/2 = 2006 - # 使用区域中心X = (200+880)/2 = 540,Y = 2006(红色区域中心) - rx = int( - getattr(analyser, "resolution_ratio_x", 1080) or 1080 - ) - ry = int( - getattr(analyser, "resolution_ratio_y", 2400) or 2400 - ) - # 点击红色文字区域的中心(基于截图分析优化) - click_x = int(540 * rx // 1080) # 区域中心X - click_y = int( - 2006 * ry // 2400 - ) # 红色区域中心Y(基于截图:1940+132/2=2006) - # 第一次点击 - analyser.operation.click( - analyser.device_id, click_x, click_y - ) - analyser._log_kv( - "参与", - "恢复流程:第一次点击加入粉丝团按钮(基于截图优化坐标)", - x=click_x, - y=click_y, - base_x=540, - base_y=2006, - region="(200,1940)-(880,2140)", - red_area_center_y=2006, - ) - analyser.operation.delay(0.5) # 短暂等待后立即第二次点击 - # 第二次点击:使用OCR识别"加入粉丝团"文字位置,然后点击 - # 扩大OCR识别区域以便更容易识别:使用常量 JOIN_FANSCLUB_REGION - from douyin.fudai.core.coords import JOIN_FANSCLUB_REGION - - ocr_click_success = False - try: - ( - ocr_region_x1, - ocr_region_y1, - ocr_region_x2, - ocr_region_y2, - ) = JOIN_FANSCLUB_REGION - # 截图加入粉丝团按钮区域(扩大范围) - analyser.cut_pic( - ocr_region_x1, - ocr_region_y1, - ocr_region_x2, - ocr_region_y2, - "", - "加入粉丝团按钮", - ) - - # 获取OCR原始结果(包含bbox信息) - fansclub_text = "" - fansclub_bbox = None - - try: - pic_path = analyser.operation._find_pic_path( - "加入粉丝团按钮" - ) - if pic_path and os.path.exists(pic_path): - from PIL import Image - - img = Image.open(pic_path) - img = img.convert("RGB") - import numpy as np - - img_np = np.array(img) - - if ( - getattr( - analyser.operation, "ocr_type", None - ) - == "easyocr" - ): - ocr_result = ( - analyser.operation.ocr.readtext(img_np) - ) - else: - ocr_result = analyser.operation.ocr.ocr( - img_np - ) - if ocr_result == [None]: - ocr_result = [] - - if isinstance(ocr_result, list) and ocr_result: - items = ( - ocr_result[0] - if ( - isinstance(ocr_result, list) - and len(ocr_result) == 1 - and isinstance(ocr_result[0], list) - ) - else ocr_result - ) - - for item in items: - text = "" - bbox = None - - if isinstance(item, (list, tuple)): - if len(item) >= 2: - if ( - isinstance( - item[0], (list, tuple) - ) - and len(item[0]) >= 2 - ): - bbox = item[0] - if isinstance(item[1], str): - text = item[1] - elif ( - isinstance( - item[1], (list, tuple) - ) - and len(item[1]) >= 1 - ): - bbox = ( - item[0] - if isinstance( - item[0], - (list, tuple), - ) - else None - ) - if isinstance( - item[1][0], str - ): - text = item[1][0] - - if ( - text - and ( - "加入粉丝团" in text - or "粉丝团" in text - ) - and bbox - ): - fansclub_text = text - fansclub_bbox = bbox - break - except Exception: - pass - - # 如果模式0没有找到,尝试模式1 - if not fansclub_text: - fansclub_text = str( - analyser.operation.analyse_pic_word( - "加入粉丝团按钮", 1 - ) - or "" - ) - - # 如果识别到"加入粉丝团"相关文字,使用OCR识别的文字位置点击 - if fansclub_text and ( - "加入粉丝团" in fansclub_text - or "粉丝团" in fansclub_text - ): - click_x = None - click_y = None - - # 如果获取到了bbox,使用bbox的中心位置 - if fansclub_bbox: - try: - xs = [] - ys = [] - for p in fansclub_bbox: - if ( - isinstance(p, (list, tuple)) - and len(p) >= 2 - ): - xs.append(float(p[0])) - ys.append(float(p[1])) - - if xs and ys: - bbox_center_x = (min(xs) + max(xs)) / 2 - bbox_center_y = (min(ys) + max(ys)) / 2 - full_x = ocr_region_x1 + bbox_center_x - full_y = ocr_region_y1 + bbox_center_y - click_x = int(full_x * rx // 1080) - click_y = int(full_y * ry // 2400) - except Exception: - pass - - # 如果bbox计算失败,使用OCR区域中心作为备选 - if click_x is None or click_y is None: - click_x = int( - (ocr_region_x1 + ocr_region_x2) - / 2 - * rx - // 1080 - ) - click_y = int( - (ocr_region_y1 + ocr_region_y2) - / 2 - * ry - // 2400 - ) - - analyser.operation.click( - analyser.device_id, - click_x, - click_y, - ) - analyser._log_kv( - "参与", - "恢复流程:第二次点击加入粉丝团按钮(OCR识别文字位置)", - ocr_text=fansclub_text[:50], - x=click_x, - y=click_y, - region=f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})", - used_bbox=fansclub_bbox is not None, - ) - ocr_click_success = True - else: - # OCR未识别到"加入粉丝团",记录日志 - analyser._log_kv( - "参与", - "恢复流程:OCR未识别到'加入粉丝团',使用坐标点击", - ocr_text=( - fansclub_text[:50] - if fansclub_text - else "空" - ), - level="WARNING", - ) - except Exception as e: - try: - analyser._log_kv( - "错误", - "OCR识别加入粉丝团按钮失败,使用坐标点击", - error=str(e), - error_type=type(e).__name__, - level="WARNING", - ) - except Exception: - pass - - # 如果OCR点击失败,回退到坐标点击 - if not ocr_click_success: - analyser.operation.click( - analyser.device_id, click_x, click_y - ) - analyser._log_kv( - "参与", - "恢复流程:第二次点击加入粉丝团按钮(基于截图优化坐标)", - x=click_x, - y=click_y, - ) - # 两次点击后,立即点击 (527, 567) 返回直播间 - analyser.operation.delay(0.5) # 短暂等待 - try: - rx = int( - getattr(analyser, "resolution_ratio_x", 1080) - or 1080 - ) - ry = int( - getattr(analyser, "resolution_ratio_y", 2400) - or 2400 - ) - return_x = int(527 * rx // 1080) - return_y = int(567 * ry // 2400) - analyser.operation.click( - analyser.device_id, return_x, return_y - ) - analyser._log_kv( - "参与", - "恢复流程:两次点击后,点击返回直播间", - x=return_x, - y=return_y, - base_x=527, - base_y=567, - ) - analyser.operation.delay(1.0) # 等待返回完成 - except Exception as e: - analyser._log_kv( - "参与", "恢复流程:点击返回直播间失败", error=str(e) - ) - except Exception: - # 如果新坐标失败,回退到优化后的坐标(粉丝团加入按钮) - try: - analyser.click(540, 2006) # 粉丝团加入按钮优化坐标 - except Exception: - # 最后回退到旧坐标 - try: - analyser.click(500, 2060) - except Exception: - pass - - # 等待加入流程完成(根据是否启用自动加入决定等待时间) - auto_join_enabled = getattr( - analyser, "auto_join_fansclub", False - ) - if auto_join_enabled: - # 启用自动加入:等待更长时间,让加入流程完成(可配置) - wait_s = getattr( - analyser, "fansclub_auto_join_wait_seconds", 5.0 - ) - analyser.operation.delay(wait_s) - analyser._log_kv( - "参与", - "已启用自动加入粉丝团,等待加入流程完成", - wait_seconds=wait_s, - ) - else: - # 未启用自动加入:等待较短时间后返回(可配置) - wait_s = getattr( - analyser, "fansclub_manual_wait_seconds", 3.0 - ) - analyser.operation.delay(wait_s) - analyser._log_kv( - "参与", - "未启用自动加入粉丝团,等待后返回", - wait_seconds=wait_s, - ) - - # 加入粉丝团成功后,点击 (545, 1995) 然后关闭详情页 - try: - rx = int( - getattr(analyser, "resolution_ratio_x", 1080) or 1080 - ) - ry = int( - getattr(analyser, "resolution_ratio_y", 2400) or 2400 - ) - return_x = int(545 * rx // 1080) - return_y = int(1995 * ry // 2400) - analyser.operation.click( - analyser.device_id, return_x, return_y - ) - analyser._log_kv( - "参与", - "加入粉丝团成功后,点击指定位置", - x=return_x, - y=return_y, - base_x=545, - base_y=1995, - ) - analyser.operation.delay(1.0) # 等待点击完成 - - # 关闭详情页 - analyser.click(500, 470) # 点击详情页旁边位置关闭详情页 - analyser._log_kv("参与", "关闭福袋详情", action="关闭详情") - analyser.operation.delay(1.0) # 等待关闭完成 - except Exception as e: - analyser._log_kv( - "参与", "点击指定位置或关闭详情页失败", error=str(e) - ) - - # 重新诊断阶段,确认是否还在粉丝团加入页 - try: - # 删除:避免重复阶段诊断,减少截图/adb开销 - st_after, seen_after = "", "" - analyser._log_kv( - "参与", - "已跳过点击加入粉丝团后的重复阶段诊断", - stage_before=st, - stage_after=st_after, - seen_after=seen_after, - ) - except Exception: - pass - - if st_after == "FANSCLUB_JOIN": - # 仍在粉丝团加入页,说明可能需要再次点击或等待更长时间 - if auto_join_enabled: - # 如果启用了自动加入,尝试再次点击 - analyser._log_kv( - "参与", "仍在粉丝团加入页,尝试再次点击" - ) - try: - # 基于截图优化坐标:红色区域中心Y=2006 - rx = int( - getattr( - analyser, "resolution_ratio_x", 1080 - ) - or 1080 - ) - ry = int( - getattr( - analyser, "resolution_ratio_y", 2400 - ) - or 2400 - ) - click_x = int(540 * rx // 1080) - click_y = int( - 2006 * ry // 2400 - ) # 红色区域中心Y=2006 - # 第一次点击 - analyser.operation.click( - analyser.device_id, click_x, click_y - ) - analyser._log_kv( - "参与", - "恢复流程:再次第一次点击加入粉丝团按钮(基于截图优化坐标)", - x=click_x, - y=click_y, - base_y=2006, - ) - analyser.operation.delay( - 0.5 - ) # 短暂等待后立即第二次点击 - # 第二次点击:使用OCR识别"加入粉丝团"文字位置,然后点击 - # 扩大OCR识别区域以便更容易识别:(150, 1900, 950, 2200) - ocr_click_success_retry = False - try: - ( - ocr_region_x1, - ocr_region_y1, - ocr_region_x2, - ocr_region_y2, - ) = (150, 1900, 950, 2200) - # 截图加入粉丝团按钮区域(扩大范围) - analyser.cut_pic( - ocr_region_x1, - ocr_region_y1, - ocr_region_x2, - ocr_region_y2, - "", - "加入粉丝团按钮", - ) - - # 获取OCR原始结果(包含bbox信息) - fansclub_text_retry = "" - fansclub_bbox_retry = None - - try: - pic_path = ( - analyser.operation._find_pic_path( - "加入粉丝团按钮" - ) - ) - if pic_path and os.path.exists( - pic_path - ): - from PIL import Image - - img = Image.open(pic_path) - img = img.convert("RGB") - import numpy as np - - img_np = np.array(img) - - if ( - getattr( - analyser.operation, - "ocr_type", - None, - ) - == "easyocr" - ): - ocr_result = analyser.operation.ocr.readtext( - img_np - ) - else: - ocr_result = ( - analyser.operation.ocr.ocr( - img_np - ) - ) - if ocr_result == [None]: - ocr_result = [] - - if ( - isinstance(ocr_result, list) - and ocr_result - ): - items = ( - ocr_result[0] - if ( - isinstance( - ocr_result, list - ) - and len(ocr_result) == 1 - and isinstance( - ocr_result[0], list - ) - ) - else ocr_result - ) - - for item in items: - text = "" - bbox = None - - if isinstance( - item, (list, tuple) - ): - if len(item) >= 2: - if ( - isinstance( - item[0], - ( - list, - tuple, - ), - ) - and len(item[0]) - >= 2 - ): - bbox = item[0] - if isinstance( - item[1], str - ): - text = item[ - 1 - ] - elif ( - isinstance( - item[1], - ( - list, - tuple, - ), - ) - and len(item[1]) - >= 1 - ): - bbox = ( - item[0] - if isinstance( - item[0], - ( - list, - tuple, - ), - ) - else None - ) - if isinstance( - item[1][0], - str, - ): - text = item[ - 1 - ][0] - - if ( - text - and ( - "加入粉丝团" in text - or "粉丝团" in text - ) - and bbox - ): - fansclub_text_retry = ( - text - ) - fansclub_bbox_retry = ( - bbox - ) - break - except Exception: - pass - - # 如果模式0没有找到,尝试模式1 - if not fansclub_text_retry: - fansclub_text_retry = str( - analyser.operation.analyse_pic_word( - "加入粉丝团按钮", 1 - ) - or "" - ) - - # 如果识别到"加入粉丝团"相关文字,使用OCR识别的文字位置点击 - if fansclub_text_retry and ( - "加入粉丝团" in fansclub_text_retry - or "粉丝团" in fansclub_text_retry - ): - click_x_retry = None - click_y_retry = None - - # 如果获取到了bbox,使用bbox的中心位置 - if fansclub_bbox_retry: - try: - xs = [] - ys = [] - for p in fansclub_bbox_retry: - if ( - isinstance( - p, (list, tuple) - ) - and len(p) >= 2 - ): - xs.append(float(p[0])) - ys.append(float(p[1])) - - if xs and ys: - bbox_center_x = ( - min(xs) + max(xs) - ) / 2 - bbox_center_y = ( - min(ys) + max(ys) - ) / 2 - full_x = ( - ocr_region_x1 - + bbox_center_x - ) - full_y = ( - ocr_region_y1 - + bbox_center_y - ) - click_x_retry = int( - full_x * rx // 1080 - ) - click_y_retry = int( - full_y * ry // 2400 - ) - except Exception: - pass - - # 如果bbox计算失败,使用OCR区域中心作为备选 - if ( - click_x_retry is None - or click_y_retry is None - ): - click_x_retry = int( - (ocr_region_x1 + ocr_region_x2) - / 2 - * rx - // 1080 - ) - click_y_retry = int( - (ocr_region_y1 + ocr_region_y2) - / 2 - * ry - // 2400 - ) - - analyser.operation.click( - analyser.device_id, - click_x_retry, - click_y_retry, - ) - analyser._log_kv( - "参与", - "恢复流程:第二次点击加入粉丝团按钮(OCR识别文字位置)", - ocr_text=fansclub_text_retry[:50], - x=click_x_retry, - y=click_y_retry, - region=f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})", - used_bbox=fansclub_bbox_retry - is not None, - ) - ocr_click_success_retry = True - else: - # OCR未识别到"加入粉丝团",记录日志 - analyser._log_kv( - "参与", - "恢复流程:OCR未识别到'加入粉丝团',使用坐标点击", - ocr_text=( - fansclub_text_retry[:50] - if fansclub_text_retry - else "空" - ), - level="WARNING", - ) - except Exception as e: - try: - analyser._log_kv( - "错误", - "OCR识别加入粉丝团按钮失败,使用坐标点击", - error=str(e), - error_type=type(e).__name__, - level="WARNING", - ) - except Exception: - pass - - # 如果OCR点击失败,回退到坐标点击 - if not ocr_click_success_retry: - analyser.operation.click( - analyser.device_id, click_x, click_y - ) - analyser._log_kv( - "参与", - "恢复流程:第二次点击加入粉丝团按钮(基于截图优化坐标)", - x=click_x, - y=click_y, - ) - # 两次点击后,立即点击 (527, 567) 返回直播间 - analyser.operation.delay(0.5) # 短暂等待 - try: - rx = int( - getattr( - analyser, "resolution_ratio_x", 1080 - ) - or 1080 - ) - ry = int( - getattr( - analyser, "resolution_ratio_y", 2400 - ) - or 2400 - ) - return_x = int(527 * rx // 1080) - return_y = int(567 * ry // 2400) - analyser.operation.click( - analyser.device_id, return_x, return_y - ) - analyser._log_kv( - "参与", - "恢复流程:两次点击后,点击返回直播间", - x=return_x, - y=return_y, - base_x=527, - base_y=567, - ) - analyser.operation.delay( - 1.0 - ) # 等待返回完成 - except Exception as e: - analyser._log_kv( - "参与", - "恢复流程:点击返回直播间失败", - error=str(e), - ) - except Exception: - pass - except Exception: - pass - return _recover_to_fudai_detail_after_fansclub() - - return True + return handle_fansclub_branch(analyser, attend_button_text) elif attend_button_text and "开始观看" in attend_button_text: # 基于截图优化坐标:OCR区域(306,2030)-(780,2110),尺寸474x80 # 区域中心X = (306+780)/2 = 543,Y = (2030+2110)/2 = 2070 diff --git a/douyin/fudai/core/fudai_attend_pkg/__init__.py b/douyin/fudai/core/fudai_attend_pkg/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/douyin/fudai/core/fudai_attend_pkg/fansclub_handler.py b/douyin/fudai/core/fudai_attend_pkg/fansclub_handler.py new file mode 100644 index 0000000..9b7c6ba --- /dev/null +++ b/douyin/fudai/core/fudai_attend_pkg/fansclub_handler.py @@ -0,0 +1,1070 @@ +"""douyin/fudai/core/fudai_attend_pkg/fansclub_handler - 粉丝团门槛分支 + +attend_choujiang 中"加入粉丝团/粉丝团"按钮分支的处理逻辑。原本是 1057 行 elif 块, +内嵌一个 _recover_to_fudai_detail_after_fansclub 闭包做"加入页"恢复。 + +入口:handle_fansclub_branch(analyser, attend_button_text) -> bool +返回 True(与原 elif 的 return True 一致)。 +""" +from __future__ import annotations + +import os +from typing import Any + +from douyin.core import path_config + + +def handle_fansclub_branch(analyser: Any, attend_button_text: str) -> bool: + """处理"需要粉丝团门槛"分支:先点参与按钮 → OCR 找加入粉丝团按钮 → 点击 → 关闭详情 → 等待 → 恢复 → 返回 True。""" + analyser.last_attend_fail_reason = "fansclub_required" + + # 保存debug截图:标注OCR识别区域(参与按钮区域) + try: + from douyin.handlers import douyin_screenshot_manager + + pic_path = path_config.get_screenshot_path() + if os.path.exists(pic_path): + from PIL import Image + + pic = Image.open(pic_path) + pic.load() + pic_rgb = pic.convert("RGB") + width, height = pic_rgb.size + rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) + ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) + # 缩放OCR区域坐标到实际分辨率 + ocr_x1 = int(306 * width / rx) + ocr_y1 = int(2030 * height / ry) + ocr_x2 = int(780 * width / rx) + ocr_y2 = int(2110 * height / ry) + # 保存debug截图 + debug_path = douyin_screenshot_manager.save_debug_image( + pic_rgb, + operation_type="ocr", + picname="参与按钮", + step="识别参与按钮", + coords=(ocr_x1, ocr_y1, ocr_x2, ocr_y2), + extra_info={ + "ocr_text": attend_button_text[:50], + "region": "(306,2030)-(780,2110)", + "result": "需要粉丝团", + }, + ) + except Exception: + pass + + # 第一步:先点击参与按钮(基于OCR区域中心:OCR区域(306,2030)-(780,2110),区域中心(543, 2070)) + analyser.click(543, 2070) + analyser._log_kv( + "参与", + "粉丝团门槛:先点击参与按钮", + result="需要粉丝团", + base_x=543, + base_y=2070, + region="(306,2030)-(780,2110)", + ) + analyser.operation.delay(1.0) # 等待参与按钮响应稍长一些,避免过快 + + # 第二步:使用OCR识别"加入粉丝团"按钮位置并点击(使用OCR识别的文字位置) + try: + rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) + ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) + + # OCR识别区域(扩大范围以便更容易识别) + ocr_region_x1, ocr_region_y1, ocr_region_x2, ocr_region_y2 = ( + 150, + 1900, + 950, + 2200, + ) + analyser.cut_pic( + ocr_region_x1, + ocr_region_y1, + ocr_region_x2, + ocr_region_y2, + "", + "加入粉丝团按钮", + ) + + # 获取OCR原始结果(包含bbox信息) + fansclub_text = "" + fansclub_bbox = None + + # 尝试模式0 + try: + # 获取裁剪后的图片路径 + pic_path = analyser.operation._find_pic_path("加入粉丝团按钮") + if pic_path and os.path.exists(pic_path): + from PIL import Image + + img = Image.open(pic_path) + img = img.convert("RGB") + import numpy as np + + img_np = np.array(img) + + # 调用OCR获取原始结果 + if getattr(analyser.operation, "ocr_type", None) == "easyocr": + ocr_result = analyser.operation.ocr.readtext(img_np) + else: + ocr_result = analyser.operation.ocr.ocr(img_np) + if ocr_result == [None]: + ocr_result = [] + + # 从OCR结果中查找"加入粉丝团"或"粉丝团"文字及其bbox + if isinstance(ocr_result, list) and ocr_result: + # PaddleOCR格式:[[[box], (text, score)], ...] + # EasyOCR格式:[(bbox, text, confidence), ...] + items = ( + ocr_result[0] + if ( + isinstance(ocr_result, list) + and len(ocr_result) == 1 + and isinstance(ocr_result[0], list) + ) + else ocr_result + ) + + for item in items: + text = "" + bbox = None + + # 提取文本和bbox + if isinstance(item, (list, tuple)): + if len(item) >= 2: + # EasyOCR格式:[(bbox, text, confidence), ...] + if ( + isinstance(item[0], (list, tuple)) + and len(item[0]) >= 2 + ): + bbox = item[0] # bbox是第一个元素 + if isinstance(item[1], str): + text = item[1] + # PaddleOCR格式:[box, (text, score)] + elif ( + isinstance(item[1], (list, tuple)) + and len(item[1]) >= 1 + ): + bbox = ( + item[0] + if isinstance(item[0], (list, tuple)) + else None + ) + if isinstance(item[1][0], str): + text = item[1][0] + + # 检查是否包含"加入粉丝团"或"粉丝团" + if ( + text + and ("加入粉丝团" in text or "粉丝团" in text) + and bbox + ): + fansclub_text = text + fansclub_bbox = bbox + break + except Exception as e: + analyser._log_kv( + "参与", "获取OCR原始结果失败", error=str(e), level="WARNING" + ) + + # 如果模式0没有找到,尝试模式1(使用analyse_pic_word) + if not fansclub_text: + fansclub_text = str( + analyser.operation.analyse_pic_word("加入粉丝团按钮", 1) or "" + ) + + # 保存debug截图:标注OCR识别区域(加入粉丝团按钮区域) + try: + from douyin.handlers import douyin_screenshot_manager + + pic_path = path_config.get_screenshot_path() + if os.path.exists(pic_path): + from PIL import Image + + pic = Image.open(pic_path) + pic.load() + pic_rgb = pic.convert("RGB") + width, height = pic_rgb.size + # 缩放OCR区域坐标到实际分辨率 + ocr_x1 = int(ocr_region_x1 * width / rx) + ocr_y1 = int(ocr_region_y1 * height / ry) + ocr_x2 = int(ocr_region_x2 * width / rx) + ocr_y2 = int(ocr_region_y2 * height / ry) + # 保存debug截图 + debug_path = douyin_screenshot_manager.save_debug_image( + pic_rgb, + operation_type="ocr", + picname="加入粉丝团按钮", + step="识别加入粉丝团按钮", + coords=(ocr_x1, ocr_y1, ocr_x2, ocr_y2), + extra_info={ + "ocr_text": fansclub_text[:50] if fansclub_text else "", + "region": f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})", + "result": ( + "识别成功" + if fansclub_text + and ( + "加入粉丝团" in fansclub_text + or "粉丝团" in fansclub_text + ) + else "识别失败" + ), + "has_bbox": fansclub_bbox is not None, + }, + ) + except Exception: + pass + + # 如果识别到"加入粉丝团"相关文字,使用OCR识别的文字位置点击 + if fansclub_text and ( + "加入粉丝团" in fansclub_text or "粉丝团" in fansclub_text + ): + click_x = None + click_y = None + + # 如果获取到了bbox,使用bbox的中心位置 + if fansclub_bbox: + try: + # 提取bbox的坐标点 + xs = [] + ys = [] + for p in fansclub_bbox: + if isinstance(p, (list, tuple)) and len(p) >= 2: + xs.append(float(p[0])) + ys.append(float(p[1])) + + if xs and ys: + # 计算bbox中心(在裁剪图片中的坐标) + bbox_center_x = (min(xs) + max(xs)) / 2 + bbox_center_y = (min(ys) + max(ys)) / 2 + + # 将裁剪图片坐标转换为全屏坐标 + # 需要加上OCR区域的偏移 + full_x = ocr_region_x1 + bbox_center_x + full_y = ocr_region_y1 + bbox_center_y + + # 缩放到实际分辨率 + click_x = int(full_x * rx // 1080) + click_y = int(full_y * ry // 2400) + except Exception as e: + analyser._log_kv( + "参与", + "计算bbox中心失败", + error=str(e), + level="WARNING", + ) + + # 如果bbox计算失败,使用OCR区域中心作为备选 + if click_x is None or click_y is None: + click_x = int((ocr_region_x1 + ocr_region_x2) / 2 * rx // 1080) + click_y = int((ocr_region_y1 + ocr_region_y2) / 2 * ry // 2400) + + analyser.operation.click(analyser.device_id, click_x, click_y) + analyser._log_kv( + "参与", + "粉丝团门槛:点击加入粉丝团按钮(OCR识别文字位置)", + ocr_text=fansclub_text[:50], + x=click_x, + y=click_y, + base_x=( + int((ocr_region_x1 + ocr_region_x2) / 2) + if click_x is None + else None + ), + base_y=( + int((ocr_region_y1 + ocr_region_y2) / 2) + if click_y is None + else None + ), + region=f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})", + used_bbox=fansclub_bbox is not None, + ) + else: + # OCR未识别到"加入粉丝团",使用OCR区域中心作为备选 + region_center_x = int( + (ocr_region_x1 + ocr_region_x2) / 2 * rx // 1080 + ) + region_center_y = int( + (ocr_region_y1 + ocr_region_y2) / 2 * ry // 2400 + ) + analyser.operation.click( + analyser.device_id, region_center_x, region_center_y + ) + analyser._log_kv( + "参与", + "粉丝团门槛:点击加入粉丝团按钮(OCR未识别到文字,使用区域中心)", + ocr_text=fansclub_text[:50] if fansclub_text else "", + x=region_center_x, + y=region_center_y, + base_x=(ocr_region_x1 + ocr_region_x2) // 2, + base_y=(ocr_region_y1 + ocr_region_y2) // 2, + region=f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})", + ) + # 等待点击完成(使用可配置延迟) + analyser.operation.delay(getattr(analyser, "fansclub_click_delay", 1.2)) + except Exception as e: + analyser._log_kv("参与", "点击加入粉丝团按钮失败", error=str(e)) + + # 第三步:关闭详情页 + analyser.click(500, 470) # 点击详情页旁边位置关闭详情页 + analyser._log_kv("参与", "关闭福袋详情", action="关闭详情") + + if not analyser.auto_join_fansclub: + analyser._log_kv( + "参与", "未启用自动加粉丝团:等待手动确认", wait_seconds=15 + ) + analyser.operation.delay(15) + + # 点击粉丝团按钮后,可能进入"加入粉丝团"独立页面:需要在该页再次点击"加入粉丝团"才能成功。 + def _recover_to_fudai_detail_after_fansclub(max_steps: int = 4) -> bool: + for i in range(int(max_steps or 4)): + try: + analyser._shot_and_diagnose( + "粉丝团", + "粉丝团后定位福袋详情({}/{})".format(i + 1, max_steps), + analyser.device_id, + ) + except Exception: + pass + try: + # 已在打开详情时完成阶段诊断,后续不再重复调用 + st, seen = "", "" + except Exception: + st, seen = "", "" + + if st == "FUDai_DETAIL": + return True + + if st == "FANSCLUB_JOIN": + # 在加入页点击底部"加入粉丝团"按钮(与详情页按钮同位置) + analyser._log_kv( + "参与", + "粉丝团加入页:点击加入粉丝团", + stage=st, + seen=seen, + attempt=i + 1, + ) + try: + # 点击加入粉丝团按钮 + # 基于实际截图分析:OCR区域 (200, 1940, 880, 2140),尺寸680x200 + # 按钮上部66%是红色区域(文字"加入粉丝团"所在),高度约132像素 + # 红色区域Y范围:1940 到 2072,中心Y = 1940 + 132/2 = 2006 + # 使用区域中心X = (200+880)/2 = 540,Y = 2006(红色区域中心) + rx = int( + getattr(analyser, "resolution_ratio_x", 1080) or 1080 + ) + ry = int( + getattr(analyser, "resolution_ratio_y", 2400) or 2400 + ) + # 点击红色文字区域的中心(基于截图分析优化) + click_x = int(540 * rx // 1080) # 区域中心X + click_y = int( + 2006 * ry // 2400 + ) # 红色区域中心Y(基于截图:1940+132/2=2006) + # 第一次点击 + analyser.operation.click( + analyser.device_id, click_x, click_y + ) + analyser._log_kv( + "参与", + "恢复流程:第一次点击加入粉丝团按钮(基于截图优化坐标)", + x=click_x, + y=click_y, + base_x=540, + base_y=2006, + region="(200,1940)-(880,2140)", + red_area_center_y=2006, + ) + analyser.operation.delay(0.5) # 短暂等待后立即第二次点击 + # 第二次点击:使用OCR识别"加入粉丝团"文字位置,然后点击 + # 扩大OCR识别区域以便更容易识别:使用常量 JOIN_FANSCLUB_REGION + from douyin.fudai.core.coords import JOIN_FANSCLUB_REGION + + ocr_click_success = False + try: + ( + ocr_region_x1, + ocr_region_y1, + ocr_region_x2, + ocr_region_y2, + ) = JOIN_FANSCLUB_REGION + # 截图加入粉丝团按钮区域(扩大范围) + analyser.cut_pic( + ocr_region_x1, + ocr_region_y1, + ocr_region_x2, + ocr_region_y2, + "", + "加入粉丝团按钮", + ) + + # 获取OCR原始结果(包含bbox信息) + fansclub_text = "" + fansclub_bbox = None + + try: + pic_path = analyser.operation._find_pic_path( + "加入粉丝团按钮" + ) + if pic_path and os.path.exists(pic_path): + from PIL import Image + + img = Image.open(pic_path) + img = img.convert("RGB") + import numpy as np + + img_np = np.array(img) + + if ( + getattr( + analyser.operation, "ocr_type", None + ) + == "easyocr" + ): + ocr_result = ( + analyser.operation.ocr.readtext(img_np) + ) + else: + ocr_result = analyser.operation.ocr.ocr( + img_np + ) + if ocr_result == [None]: + ocr_result = [] + + if isinstance(ocr_result, list) and ocr_result: + items = ( + ocr_result[0] + if ( + isinstance(ocr_result, list) + and len(ocr_result) == 1 + and isinstance(ocr_result[0], list) + ) + else ocr_result + ) + + for item in items: + text = "" + bbox = None + + if isinstance(item, (list, tuple)): + if len(item) >= 2: + if ( + isinstance( + item[0], (list, tuple) + ) + and len(item[0]) >= 2 + ): + bbox = item[0] + if isinstance(item[1], str): + text = item[1] + elif ( + isinstance( + item[1], (list, tuple) + ) + and len(item[1]) >= 1 + ): + bbox = ( + item[0] + if isinstance( + item[0], + (list, tuple), + ) + else None + ) + if isinstance( + item[1][0], str + ): + text = item[1][0] + + if ( + text + and ( + "加入粉丝团" in text + or "粉丝团" in text + ) + and bbox + ): + fansclub_text = text + fansclub_bbox = bbox + break + except Exception: + pass + + # 如果模式0没有找到,尝试模式1 + if not fansclub_text: + fansclub_text = str( + analyser.operation.analyse_pic_word( + "加入粉丝团按钮", 1 + ) + or "" + ) + + # 如果识别到"加入粉丝团"相关文字,使用OCR识别的文字位置点击 + if fansclub_text and ( + "加入粉丝团" in fansclub_text + or "粉丝团" in fansclub_text + ): + click_x = None + click_y = None + + # 如果获取到了bbox,使用bbox的中心位置 + if fansclub_bbox: + try: + xs = [] + ys = [] + for p in fansclub_bbox: + if ( + isinstance(p, (list, tuple)) + and len(p) >= 2 + ): + xs.append(float(p[0])) + ys.append(float(p[1])) + + if xs and ys: + bbox_center_x = (min(xs) + max(xs)) / 2 + bbox_center_y = (min(ys) + max(ys)) / 2 + full_x = ocr_region_x1 + bbox_center_x + full_y = ocr_region_y1 + bbox_center_y + click_x = int(full_x * rx // 1080) + click_y = int(full_y * ry // 2400) + except Exception: + pass + + # 如果bbox计算失败,使用OCR区域中心作为备选 + if click_x is None or click_y is None: + click_x = int( + (ocr_region_x1 + ocr_region_x2) + / 2 + * rx + // 1080 + ) + click_y = int( + (ocr_region_y1 + ocr_region_y2) + / 2 + * ry + // 2400 + ) + + analyser.operation.click( + analyser.device_id, + click_x, + click_y, + ) + analyser._log_kv( + "参与", + "恢复流程:第二次点击加入粉丝团按钮(OCR识别文字位置)", + ocr_text=fansclub_text[:50], + x=click_x, + y=click_y, + region=f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})", + used_bbox=fansclub_bbox is not None, + ) + ocr_click_success = True + else: + # OCR未识别到"加入粉丝团",记录日志 + analyser._log_kv( + "参与", + "恢复流程:OCR未识别到'加入粉丝团',使用坐标点击", + ocr_text=( + fansclub_text[:50] + if fansclub_text + else "空" + ), + level="WARNING", + ) + except Exception as e: + try: + analyser._log_kv( + "错误", + "OCR识别加入粉丝团按钮失败,使用坐标点击", + error=str(e), + error_type=type(e).__name__, + level="WARNING", + ) + except Exception: + pass + + # 如果OCR点击失败,回退到坐标点击 + if not ocr_click_success: + analyser.operation.click( + analyser.device_id, click_x, click_y + ) + analyser._log_kv( + "参与", + "恢复流程:第二次点击加入粉丝团按钮(基于截图优化坐标)", + x=click_x, + y=click_y, + ) + # 两次点击后,立即点击 (527, 567) 返回直播间 + analyser.operation.delay(0.5) # 短暂等待 + try: + rx = int( + getattr(analyser, "resolution_ratio_x", 1080) + or 1080 + ) + ry = int( + getattr(analyser, "resolution_ratio_y", 2400) + or 2400 + ) + return_x = int(527 * rx // 1080) + return_y = int(567 * ry // 2400) + analyser.operation.click( + analyser.device_id, return_x, return_y + ) + analyser._log_kv( + "参与", + "恢复流程:两次点击后,点击返回直播间", + x=return_x, + y=return_y, + base_x=527, + base_y=567, + ) + analyser.operation.delay(1.0) # 等待返回完成 + except Exception as e: + analyser._log_kv( + "参与", "恢复流程:点击返回直播间失败", error=str(e) + ) + except Exception: + # 如果新坐标失败,回退到优化后的坐标(粉丝团加入按钮) + try: + analyser.click(540, 2006) # 粉丝团加入按钮优化坐标 + except Exception: + # 最后回退到旧坐标 + try: + analyser.click(500, 2060) + except Exception: + pass + + # 等待加入流程完成(根据是否启用自动加入决定等待时间) + auto_join_enabled = getattr( + analyser, "auto_join_fansclub", False + ) + if auto_join_enabled: + # 启用自动加入:等待更长时间,让加入流程完成(可配置) + wait_s = getattr( + analyser, "fansclub_auto_join_wait_seconds", 5.0 + ) + analyser.operation.delay(wait_s) + analyser._log_kv( + "参与", + "已启用自动加入粉丝团,等待加入流程完成", + wait_seconds=wait_s, + ) + else: + # 未启用自动加入:等待较短时间后返回(可配置) + wait_s = getattr( + analyser, "fansclub_manual_wait_seconds", 3.0 + ) + analyser.operation.delay(wait_s) + analyser._log_kv( + "参与", + "未启用自动加入粉丝团,等待后返回", + wait_seconds=wait_s, + ) + + # 加入粉丝团成功后,点击 (545, 1995) 然后关闭详情页 + try: + rx = int( + getattr(analyser, "resolution_ratio_x", 1080) or 1080 + ) + ry = int( + getattr(analyser, "resolution_ratio_y", 2400) or 2400 + ) + return_x = int(545 * rx // 1080) + return_y = int(1995 * ry // 2400) + analyser.operation.click( + analyser.device_id, return_x, return_y + ) + analyser._log_kv( + "参与", + "加入粉丝团成功后,点击指定位置", + x=return_x, + y=return_y, + base_x=545, + base_y=1995, + ) + analyser.operation.delay(1.0) # 等待点击完成 + + # 关闭详情页 + analyser.click(500, 470) # 点击详情页旁边位置关闭详情页 + analyser._log_kv("参与", "关闭福袋详情", action="关闭详情") + analyser.operation.delay(1.0) # 等待关闭完成 + except Exception as e: + analyser._log_kv( + "参与", "点击指定位置或关闭详情页失败", error=str(e) + ) + + # 重新诊断阶段,确认是否还在粉丝团加入页 + try: + # 删除:避免重复阶段诊断,减少截图/adb开销 + st_after, seen_after = "", "" + analyser._log_kv( + "参与", + "已跳过点击加入粉丝团后的重复阶段诊断", + stage_before=st, + stage_after=st_after, + seen_after=seen_after, + ) + except Exception: + pass + + if st_after == "FANSCLUB_JOIN": + # 仍在粉丝团加入页,说明可能需要再次点击或等待更长时间 + if auto_join_enabled: + # 如果启用了自动加入,尝试再次点击 + analyser._log_kv( + "参与", "仍在粉丝团加入页,尝试再次点击" + ) + try: + # 基于截图优化坐标:红色区域中心Y=2006 + rx = int( + getattr( + analyser, "resolution_ratio_x", 1080 + ) + or 1080 + ) + ry = int( + getattr( + analyser, "resolution_ratio_y", 2400 + ) + or 2400 + ) + click_x = int(540 * rx // 1080) + click_y = int( + 2006 * ry // 2400 + ) # 红色区域中心Y=2006 + # 第一次点击 + analyser.operation.click( + analyser.device_id, click_x, click_y + ) + analyser._log_kv( + "参与", + "恢复流程:再次第一次点击加入粉丝团按钮(基于截图优化坐标)", + x=click_x, + y=click_y, + base_y=2006, + ) + analyser.operation.delay( + 0.5 + ) # 短暂等待后立即第二次点击 + # 第二次点击:使用OCR识别"加入粉丝团"文字位置,然后点击 + # 扩大OCR识别区域以便更容易识别:(150, 1900, 950, 2200) + ocr_click_success_retry = False + try: + ( + ocr_region_x1, + ocr_region_y1, + ocr_region_x2, + ocr_region_y2, + ) = (150, 1900, 950, 2200) + # 截图加入粉丝团按钮区域(扩大范围) + analyser.cut_pic( + ocr_region_x1, + ocr_region_y1, + ocr_region_x2, + ocr_region_y2, + "", + "加入粉丝团按钮", + ) + + # 获取OCR原始结果(包含bbox信息) + fansclub_text_retry = "" + fansclub_bbox_retry = None + + try: + pic_path = ( + analyser.operation._find_pic_path( + "加入粉丝团按钮" + ) + ) + if pic_path and os.path.exists( + pic_path + ): + from PIL import Image + + img = Image.open(pic_path) + img = img.convert("RGB") + import numpy as np + + img_np = np.array(img) + + if ( + getattr( + analyser.operation, + "ocr_type", + None, + ) + == "easyocr" + ): + ocr_result = analyser.operation.ocr.readtext( + img_np + ) + else: + ocr_result = ( + analyser.operation.ocr.ocr( + img_np + ) + ) + if ocr_result == [None]: + ocr_result = [] + + if ( + isinstance(ocr_result, list) + and ocr_result + ): + items = ( + ocr_result[0] + if ( + isinstance( + ocr_result, list + ) + and len(ocr_result) == 1 + and isinstance( + ocr_result[0], list + ) + ) + else ocr_result + ) + + for item in items: + text = "" + bbox = None + + if isinstance( + item, (list, tuple) + ): + if len(item) >= 2: + if ( + isinstance( + item[0], + ( + list, + tuple, + ), + ) + and len(item[0]) + >= 2 + ): + bbox = item[0] + if isinstance( + item[1], str + ): + text = item[ + 1 + ] + elif ( + isinstance( + item[1], + ( + list, + tuple, + ), + ) + and len(item[1]) + >= 1 + ): + bbox = ( + item[0] + if isinstance( + item[0], + ( + list, + tuple, + ), + ) + else None + ) + if isinstance( + item[1][0], + str, + ): + text = item[ + 1 + ][0] + + if ( + text + and ( + "加入粉丝团" in text + or "粉丝团" in text + ) + and bbox + ): + fansclub_text_retry = ( + text + ) + fansclub_bbox_retry = ( + bbox + ) + break + except Exception: + pass + + # 如果模式0没有找到,尝试模式1 + if not fansclub_text_retry: + fansclub_text_retry = str( + analyser.operation.analyse_pic_word( + "加入粉丝团按钮", 1 + ) + or "" + ) + + # 如果识别到"加入粉丝团"相关文字,使用OCR识别的文字位置点击 + if fansclub_text_retry and ( + "加入粉丝团" in fansclub_text_retry + or "粉丝团" in fansclub_text_retry + ): + click_x_retry = None + click_y_retry = None + + # 如果获取到了bbox,使用bbox的中心位置 + if fansclub_bbox_retry: + try: + xs = [] + ys = [] + for p in fansclub_bbox_retry: + if ( + isinstance( + p, (list, tuple) + ) + and len(p) >= 2 + ): + xs.append(float(p[0])) + ys.append(float(p[1])) + + if xs and ys: + bbox_center_x = ( + min(xs) + max(xs) + ) / 2 + bbox_center_y = ( + min(ys) + max(ys) + ) / 2 + full_x = ( + ocr_region_x1 + + bbox_center_x + ) + full_y = ( + ocr_region_y1 + + bbox_center_y + ) + click_x_retry = int( + full_x * rx // 1080 + ) + click_y_retry = int( + full_y * ry // 2400 + ) + except Exception: + pass + + # 如果bbox计算失败,使用OCR区域中心作为备选 + if ( + click_x_retry is None + or click_y_retry is None + ): + click_x_retry = int( + (ocr_region_x1 + ocr_region_x2) + / 2 + * rx + // 1080 + ) + click_y_retry = int( + (ocr_region_y1 + ocr_region_y2) + / 2 + * ry + // 2400 + ) + + analyser.operation.click( + analyser.device_id, + click_x_retry, + click_y_retry, + ) + analyser._log_kv( + "参与", + "恢复流程:第二次点击加入粉丝团按钮(OCR识别文字位置)", + ocr_text=fansclub_text_retry[:50], + x=click_x_retry, + y=click_y_retry, + region=f"({ocr_region_x1},{ocr_region_y1})-({ocr_region_x2},{ocr_region_y2})", + used_bbox=fansclub_bbox_retry + is not None, + ) + ocr_click_success_retry = True + else: + # OCR未识别到"加入粉丝团",记录日志 + analyser._log_kv( + "参与", + "恢复流程:OCR未识别到'加入粉丝团',使用坐标点击", + ocr_text=( + fansclub_text_retry[:50] + if fansclub_text_retry + else "空" + ), + level="WARNING", + ) + except Exception as e: + try: + analyser._log_kv( + "错误", + "OCR识别加入粉丝团按钮失败,使用坐标点击", + error=str(e), + error_type=type(e).__name__, + level="WARNING", + ) + except Exception: + pass + + # 如果OCR点击失败,回退到坐标点击 + if not ocr_click_success_retry: + analyser.operation.click( + analyser.device_id, click_x, click_y + ) + analyser._log_kv( + "参与", + "恢复流程:第二次点击加入粉丝团按钮(基于截图优化坐标)", + x=click_x, + y=click_y, + ) + # 两次点击后,立即点击 (527, 567) 返回直播间 + analyser.operation.delay(0.5) # 短暂等待 + try: + rx = int( + getattr( + analyser, "resolution_ratio_x", 1080 + ) + or 1080 + ) + ry = int( + getattr( + analyser, "resolution_ratio_y", 2400 + ) + or 2400 + ) + return_x = int(527 * rx // 1080) + return_y = int(567 * ry // 2400) + analyser.operation.click( + analyser.device_id, return_x, return_y + ) + analyser._log_kv( + "参与", + "恢复流程:两次点击后,点击返回直播间", + x=return_x, + y=return_y, + base_x=527, + base_y=567, + ) + analyser.operation.delay( + 1.0 + ) # 等待返回完成 + except Exception as e: + analyser._log_kv( + "参与", + "恢复流程:点击返回直播间失败", + error=str(e), + ) + except Exception: + pass + except Exception: + pass + return _recover_to_fudai_detail_after_fansclub() + return True diff --git a/tests/test_fansclub_handler.py b/tests/test_fansclub_handler.py new file mode 100644 index 0000000..98c0ab1 --- /dev/null +++ b/tests/test_fansclub_handler.py @@ -0,0 +1,115 @@ +"""douyin/fudai/core/fudai_attend_pkg/fansclub_handler 单元测试。 + +主要验证: +- handle_fansclub_branch 总是返回 True +- 设置 analyser.last_attend_fail_reason = "fansclub_required" +- 在路径上点击参与按钮 (543, 2070) +- 在路径上点击关闭详情 (500, 470) +- 异常路径不抛 +""" +from __future__ import annotations + +from unittest.mock import MagicMock, patch + +import pytest + +from douyin.fudai.core.fudai_attend_pkg.fansclub_handler import ( + handle_fansclub_branch, +) + + +def _mk_analyser(*, auto_join_fansclub: bool = False): + """构造一个 attend 流程能跑通的 mock analyser。""" + a = MagicMock() + a.last_attend_fail_reason = "" + a.auto_join_fansclub = bool(auto_join_fansclub) + a.resolution_ratio_x = 1080 + a.resolution_ratio_y = 2400 + a.device_id = "MOCK" + a.fansclub_click_delay = 0.0 # 单测里跳过实际延迟 + a.fansclub_auto_join_wait_seconds = 0.0 + a.fansclub_manual_wait_seconds = 0.0 + + # operation 的方法都返回非 None / "" 让流程顺利 + a.operation = MagicMock() + a.operation.delay = MagicMock(return_value=None) + a.operation.click = MagicMock(return_value=None) + a.operation.click_back = MagicMock(return_value=None) + a.operation.analyse_pic_word = MagicMock(return_value="") # OCR 不识别 → 走坐标兜底 + a.operation.analyse_pic_digits = MagicMock(return_value="") + a.operation.ocr = MagicMock() + a.operation.ocr.ocr = MagicMock(return_value=[]) + a.operation.ocr.readtext = MagicMock(return_value=[]) + a.operation._find_pic_path = MagicMock(return_value="") + a.cut_pic = MagicMock(return_value=True) + a.click = MagicMock(return_value=None) + a._log_kv = MagicMock(return_value=None) + a._shot_and_diagnose = MagicMock(return_value=None) + return a + + +class TestHandleFansclubBranch: + def test_returns_true(self): + a = _mk_analyser() + result = handle_fansclub_branch(a, "加入粉丝团") + assert result is True + + def test_sets_fail_reason(self): + a = _mk_analyser() + handle_fansclub_branch(a, "加入粉丝团") + assert a.last_attend_fail_reason == "fansclub_required" + + def test_clicks_attend_button_at_543_2070(self): + """第一步必须点参与按钮 (543, 2070)。""" + a = _mk_analyser() + handle_fansclub_branch(a, "加入粉丝团") + # 找 analyser.click(543, 2070) 这一调用 + attend_calls = [ + c for c in a.click.call_args_list if c.args == (543, 2070) + ] + assert len(attend_calls) >= 1 + + def test_closes_detail_at_500_470(self): + """第三步必须点 (500, 470) 关闭详情。""" + a = _mk_analyser() + handle_fansclub_branch(a, "加入粉丝团") + close_calls = [ + c for c in a.click.call_args_list if c.args == (500, 470) + ] + assert len(close_calls) >= 1 + + def test_handles_粉丝团_text_only(self): + """attend_button_text 含 "粉丝团" 但不含 "加入" 也走该分支。""" + a = _mk_analyser() + result = handle_fansclub_branch(a, "粉丝团门槛") + assert result is True + + def test_does_not_raise_when_screenshot_missing(self): + """path_config.get_screenshot_path 不存在时不应抛。""" + a = _mk_analyser() + with patch("os.path.exists", return_value=False): + result = handle_fansclub_branch(a, "加入粉丝团") + assert result is True + + def test_does_not_raise_when_ocr_throws(self): + """OCR 全部抛异常时仍正常返回 True(不传播)。""" + a = _mk_analyser() + a.operation.analyse_pic_word = MagicMock(side_effect=RuntimeError("ocr fail")) + a.operation.ocr.ocr = MagicMock(side_effect=RuntimeError("ocr fail")) + a.operation.ocr.readtext = MagicMock(side_effect=RuntimeError("ocr fail")) + result = handle_fansclub_branch(a, "加入粉丝团") + assert result is True + + def test_auto_join_disabled_does_not_wait_long(self): + """未启用自动加入时也走完整流程,返回 True。""" + a = _mk_analyser(auto_join_fansclub=False) + result = handle_fansclub_branch(a, "加入粉丝团") + assert result is True + # auto_join 关闭时应当走"等待手动确认"日志 + log_msgs = [str(c) for c in a._log_kv.call_args_list] + assert any("未启用自动加粉丝团" in m for m in log_msgs) + + def test_auto_join_enabled(self): + a = _mk_analyser(auto_join_fansclub=True) + result = handle_fansclub_branch(a, "加入粉丝团") + assert result is True