feat: Introduce unified logging system and optimize file management
- Added a new unified logging module to standardize log formatting, including support for traceId and MDC for better tracking. - Updated `.gitignore` to exclude code analysis reports and temporary files. - Created cleanup scripts to manage unused files and generate cleanup reports. - Enhanced existing modules to integrate the new logging system and improve debugging capabilities. - Removed outdated files and scripts to streamline the project structure.
This commit is contained in:
1 parent
08a0b41834
commit
e5a510d19b
45 files changed
+18285
-1357
No files matched your search
@@ -1,74 +0,0 @@
|
||||
import sys
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def auto_fix_indentation(path: Path, indent_size: int = 4) -> int:
|
||||
"""Naively fix lines whose indentation is not deeper than a preceding colon line.
|
||||
|
||||
Heuristic:
|
||||
- When a line endswith ':' (non-blank, non-comment), the next non-empty line
|
||||
that is not an 'else/elif/except/finally' should be indented strictly more.
|
||||
- If it is not, increase its leading spaces to (prev_indent + indent_size).
|
||||
This is a best-effort fixer for common mistakes that cause IndentationError.
|
||||
"""
|
||||
lines = path.read_text(encoding="utf-8").splitlines()
|
||||
fixes = 0
|
||||
|
||||
def leading_spaces(s: str) -> int:
|
||||
return len(s) - len(s.lstrip(" "))
|
||||
|
||||
for i in range(len(lines) - 1):
|
||||
cur = lines[i]
|
||||
nxt = lines[i + 1]
|
||||
cur_strip = cur.strip()
|
||||
nxt_strip = nxt.strip()
|
||||
|
||||
if not cur_strip:
|
||||
continue
|
||||
if cur_strip.startswith("#"):
|
||||
continue
|
||||
if not cur_strip.endswith(":"):
|
||||
continue
|
||||
|
||||
# skip multi-colon lines like dicts etc. Simple heuristic: has space before colon.
|
||||
# We still treat most control statements/defs.
|
||||
# Skip the next line if it's empty or a comment.
|
||||
if not nxt_strip or nxt_strip.startswith("#"):
|
||||
continue
|
||||
# If next line is a peer control keyword, don't force indent.
|
||||
if nxt_strip.startswith(("else:", "elif ", "except", "finally:")):
|
||||
continue
|
||||
|
||||
cur_indent = leading_spaces(cur)
|
||||
nxt_indent = leading_spaces(nxt)
|
||||
expected = cur_indent + indent_size
|
||||
if nxt_indent <= cur_indent:
|
||||
lines[i + 1] = " " * expected + nxt_strip
|
||||
fixes += 1
|
||||
|
||||
if fixes:
|
||||
path.write_text("\n".join(lines), encoding="utf-8")
|
||||
return fixes
|
||||
|
||||
|
||||
def main():
|
||||
target = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("douyin_fudai.py")
|
||||
if not target.exists():
|
||||
print(f"File not found: {target}")
|
||||
sys.exit(1)
|
||||
|
||||
backup = target.with_suffix(target.suffix + ".bak")
|
||||
shutil.copyfile(target, backup)
|
||||
fixes = auto_fix_indentation(target)
|
||||
print(f"Auto-fix done. Applied {fixes} indentation adjustments.")
|
||||
print(f"Backup saved to: {backup}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,142 +0,0 @@
|
||||
"""
|
||||
用于查看截图文件并确认坐标位置的辅助脚本
|
||||
使用方法:
|
||||
1. 运行程序后,会打开当前截图
|
||||
2. 在图片上点击,会显示点击位置的坐标
|
||||
3. 记录你需要的区域坐标
|
||||
"""
|
||||
|
||||
import os
|
||||
from PIL import Image
|
||||
import sys
|
||||
|
||||
def show_image_coordinates(image_path):
|
||||
"""显示图片并允许用户查看坐标"""
|
||||
if not os.path.exists(image_path):
|
||||
print(f"图片文件不存在: {image_path}")
|
||||
return
|
||||
|
||||
try:
|
||||
img = Image.open(image_path)
|
||||
width, height = img.size
|
||||
print(f"\n图片信息:")
|
||||
print(f" 文件路径: {image_path}")
|
||||
print(f" 尺寸: {width} x {height} 像素")
|
||||
print(f"\n坐标说明:")
|
||||
print(f" - 坐标系原点 (0, 0) 在左上角")
|
||||
print(f" - X 轴向右递增")
|
||||
print(f" - Y 轴向下递增")
|
||||
print(f" - 格式: (x, y) 或 (x1, y1, x2, y2)")
|
||||
print(f"\n如何获取坐标:")
|
||||
print(f" 方法1: 使用Windows画图工具")
|
||||
print(f" 1. 右键点击图片 -> 打开方式 -> 画图")
|
||||
print(f" 2. 将鼠标移动到目标位置,状态栏会显示坐标 (X, Y)")
|
||||
print(f" 3. 记录左上角坐标 (x1, y1) 和右下角坐标 (x2, y2)")
|
||||
print(f"\n 方法2: 使用Python脚本交互式查看")
|
||||
print(f" 运行: python {__file__} interactive")
|
||||
print(f"\n 方法3: 使用代码获取图片尺寸")
|
||||
print(f" 当前图片尺寸: {width} x {height}")
|
||||
print(f" 你可以根据这个尺寸估算坐标")
|
||||
|
||||
# 如果是交互模式,尝试使用 tkinter 显示图片
|
||||
if len(sys.argv) > 1 and sys.argv[1] == 'interactive':
|
||||
try:
|
||||
import tkinter as tk
|
||||
from PIL import ImageTk
|
||||
|
||||
root = tk.Tk()
|
||||
root.title(f"坐标查看器 - {os.path.basename(image_path)}")
|
||||
|
||||
# 计算显示尺寸(如果图片太大,缩放显示)
|
||||
max_display_size = 1200
|
||||
display_width, display_height = width, height
|
||||
if width > max_display_size or height > max_display_size:
|
||||
scale = min(max_display_size / width, max_display_size / height)
|
||||
display_width = int(width * scale)
|
||||
display_height = int(height * scale)
|
||||
|
||||
img_resized = img.resize((display_width, display_height), Image.Resampling.LANCZOS)
|
||||
photo = ImageTk.PhotoImage(img_resized)
|
||||
|
||||
label = tk.Label(root, image=photo)
|
||||
label.pack()
|
||||
|
||||
coord_label = tk.Label(root, text="将鼠标移动到图片上查看坐标", font=("Arial", 12))
|
||||
coord_label.pack()
|
||||
|
||||
def on_mouse_move(event):
|
||||
# 将显示坐标转换为实际坐标
|
||||
if display_width != width or display_height != height:
|
||||
scale_x = width / display_width
|
||||
scale_y = height / display_height
|
||||
actual_x = int(event.x * scale_x)
|
||||
actual_y = int(event.y * scale_y)
|
||||
else:
|
||||
actual_x = event.x
|
||||
actual_y = event.y
|
||||
|
||||
coord_label.config(text=f"坐标: ({actual_x}, {actual_y}) | 显示: ({event.x}, {event.y})")
|
||||
|
||||
def on_click(event):
|
||||
# 将显示坐标转换为实际坐标
|
||||
if display_width != width or display_height != height:
|
||||
scale_x = width / display_width
|
||||
scale_y = height / display_height
|
||||
actual_x = int(event.x * scale_x)
|
||||
actual_y = int(event.y * scale_y)
|
||||
else:
|
||||
actual_x = event.x
|
||||
actual_y = event.y
|
||||
print(f"点击坐标: ({actual_x}, {actual_y})")
|
||||
coord_label.config(text=f"点击坐标: ({actual_x}, {actual_y})", fg="red")
|
||||
|
||||
label.bind("<Motion>", on_mouse_move)
|
||||
label.bind("<Button-1>", on_click)
|
||||
|
||||
print(f"\n交互窗口已打开,你可以:")
|
||||
print(f" - 移动鼠标查看坐标")
|
||||
print(f" - 点击鼠标记录坐标")
|
||||
print(f" - 关闭窗口退出")
|
||||
|
||||
root.mainloop()
|
||||
except ImportError:
|
||||
print("\n提示: 安装 tkinter 可以启用交互模式")
|
||||
print(" Windows通常自带,如果缺失可以安装 python-tk 包")
|
||||
|
||||
except Exception as e:
|
||||
print(f"打开图片失败: {e}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 默认查看 screenshot.png
|
||||
base_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
screenshot_path = os.path.join(base_dir, 'pic', 'screenshot.png')
|
||||
|
||||
if len(sys.argv) > 1 and sys.argv[1] != 'interactive':
|
||||
# 如果提供了文件路径
|
||||
image_path = sys.argv[1]
|
||||
else:
|
||||
image_path = screenshot_path
|
||||
|
||||
show_image_coordinates(image_path)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
import re
|
||||
|
||||
with open('douyin_fudai.py', 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
lines = content.split('\n')
|
||||
|
||||
# 查找所有可能的缩进问题模式
|
||||
problems = []
|
||||
for i in range(len(lines)-1):
|
||||
line = lines[i]
|
||||
next_line = lines[i+1] if i+1 < len(lines) else ''
|
||||
|
||||
stripped = line.rstrip()
|
||||
next_stripped = next_line.rstrip()
|
||||
|
||||
if not stripped or not next_stripped:
|
||||
continue
|
||||
|
||||
# 当前行缩进
|
||||
indent = len(line) - len(line.lstrip())
|
||||
next_indent = len(next_line) - len(next_line.lstrip())
|
||||
|
||||
# 如果当前行是控制语句(以冒号结尾)
|
||||
if stripped.endswith(':'):
|
||||
next_content = next_stripped.lstrip()
|
||||
# 下一行不是 else/elif/except/finally,且缩进不正确
|
||||
if next_content and not next_content.startswith(('else:', 'elif ', 'except', 'finally:')):
|
||||
if next_indent <= indent:
|
||||
problems.append((i+2, indent, next_indent, stripped[-80:], next_stripped[:80]))
|
||||
|
||||
print(f'Found {len(problems)} potential indentation problems:')
|
||||
for p in problems[:50]:
|
||||
print(f'Line {p[0]}: expected indent > {p[1]}, got {p[2]}')
|
||||
print(f' After: ...{p[3]}')
|
||||
print(f' Line: {p[4]}')
|
||||
print()
|
||||
|
||||
@@ -1,375 +0,0 @@
|
||||
"""
|
||||
OCR优化模块:支持多种OCR方案,可配置切换
|
||||
|
||||
支持的方案:
|
||||
1. PaddleOCR(当前默认,准确但较慢)
|
||||
2. EasyOCR(推荐,快速且准确)
|
||||
3. 百度OCR API(在线,极快极准,有免费额度)
|
||||
4. 腾讯OCR API(在线,极快极准,有免费额度)
|
||||
|
||||
使用方法:
|
||||
1. 设置环境变量 OCR_TYPE=easyocr 或 baidu 或 tencent
|
||||
2. 或在 config.json 中设置 "ocr_type": "easyocr"
|
||||
"""
|
||||
|
||||
import os
|
||||
import base64
|
||||
import json
|
||||
import time
|
||||
from typing import Optional, Tuple
|
||||
from PIL import Image
|
||||
import numpy as np
|
||||
|
||||
|
||||
class OCRProvider:
|
||||
"""OCR提供者基类"""
|
||||
|
||||
def __init__(self):
|
||||
self.initialized = False
|
||||
self.provider = None
|
||||
|
||||
def initialize(self):
|
||||
"""初始化OCR引擎"""
|
||||
raise NotImplementedError
|
||||
|
||||
def recognize(self, image: Image.Image) -> str:
|
||||
"""识别图片中的文字"""
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class PaddleOCRProvider(OCRProvider):
|
||||
"""PaddleOCR提供者(当前默认)"""
|
||||
|
||||
def initialize(self):
|
||||
if self.initialized:
|
||||
return
|
||||
try:
|
||||
import contextlib
|
||||
devnull = open(os.devnull, "w")
|
||||
with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(devnull):
|
||||
from paddleocr import PaddleOCR
|
||||
self.provider = PaddleOCR(
|
||||
lang="ch",
|
||||
ocr_version="PP-OCRv4",
|
||||
use_doc_orientation_classify=False,
|
||||
use_doc_unwarping=False,
|
||||
use_textline_orientation=False,
|
||||
)
|
||||
devnull.close()
|
||||
self.initialized = True
|
||||
except Exception as e:
|
||||
print(f"[OCR] PaddleOCR初始化失败: {e}")
|
||||
self.provider = None
|
||||
|
||||
def recognize(self, image: Image.Image) -> str:
|
||||
if not self.initialized:
|
||||
self.initialize()
|
||||
if self.provider is None:
|
||||
return ""
|
||||
|
||||
try:
|
||||
img_np = np.array(image.convert('RGB'))
|
||||
result = self.provider.ocr(img_np)
|
||||
if result == [None]:
|
||||
return ""
|
||||
|
||||
# 提取文本
|
||||
texts = []
|
||||
if isinstance(result, list):
|
||||
for item in result:
|
||||
if isinstance(item, list):
|
||||
for sub_item in item:
|
||||
if isinstance(sub_item, (list, tuple)) and len(sub_item) >= 2:
|
||||
text = sub_item[1]
|
||||
if isinstance(text, (list, tuple)) and len(text) >= 1:
|
||||
texts.append(str(text[0]))
|
||||
elif isinstance(text, str):
|
||||
texts.append(text)
|
||||
elif isinstance(text, dict):
|
||||
texts.append(str(text.get("text", text.get("rec_text", ""))))
|
||||
|
||||
return "".join(texts)
|
||||
except Exception as e:
|
||||
print(f"[OCR] PaddleOCR识别失败: {e}")
|
||||
return ""
|
||||
|
||||
|
||||
class EasyOCRProvider(OCRProvider):
|
||||
"""EasyOCR提供者(推荐:快速且准确)"""
|
||||
|
||||
def initialize(self):
|
||||
if self.initialized:
|
||||
return
|
||||
try:
|
||||
import easyocr
|
||||
# 只加载中文和英文,加快初始化速度
|
||||
self.provider = easyocr.Reader(['ch_sim', 'en'], gpu=False) # gpu=True 如果可用GPU
|
||||
self.initialized = True
|
||||
print("[OCR] EasyOCR初始化成功")
|
||||
except Exception as e:
|
||||
print(f"[OCR] EasyOCR初始化失败: {e}")
|
||||
print("[OCR] 请安装: pip install easyocr")
|
||||
self.provider = None
|
||||
|
||||
def recognize(self, image: Image.Image) -> str:
|
||||
if not self.initialized:
|
||||
self.initialize()
|
||||
if self.provider is None:
|
||||
return ""
|
||||
|
||||
try:
|
||||
img_np = np.array(image.convert('RGB'))
|
||||
results = self.provider.readtext(img_np)
|
||||
|
||||
# EasyOCR返回格式: [(bbox, text, confidence), ...]
|
||||
texts = [result[1] for result in results if len(result) >= 2]
|
||||
return "".join(texts)
|
||||
except Exception as e:
|
||||
print(f"[OCR] EasyOCR识别失败: {e}")
|
||||
return ""
|
||||
|
||||
|
||||
class BaiduOCRProvider(OCRProvider):
|
||||
"""百度OCR API提供者(在线,极快极准)"""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.api_key = os.environ.get("BAIDU_OCR_API_KEY", "")
|
||||
self.secret_key = os.environ.get("BAIDU_OCR_SECRET_KEY", "")
|
||||
self.access_token = None
|
||||
|
||||
def initialize(self):
|
||||
if self.initialized:
|
||||
return
|
||||
if not self.api_key or not self.secret_key:
|
||||
print("[OCR] 百度OCR API: 未设置API_KEY和SECRET_KEY")
|
||||
print("[OCR] 请设置环境变量: BAIDU_OCR_API_KEY 和 BAIDU_OCR_SECRET_KEY")
|
||||
print("[OCR] 或访问: https://ai.baidu.com/tech/ocr/general")
|
||||
return
|
||||
|
||||
try:
|
||||
import requests
|
||||
# 获取access_token
|
||||
token_url = "https://aip.baidubce.com/oauth/2.0/token"
|
||||
params = {
|
||||
"grant_type": "client_credentials",
|
||||
"client_id": self.api_key,
|
||||
"client_secret": self.secret_key
|
||||
}
|
||||
response = requests.post(token_url, params=params, timeout=5)
|
||||
if response.status_code == 200:
|
||||
self.access_token = response.json().get("access_token")
|
||||
self.initialized = True
|
||||
print("[OCR] 百度OCR API初始化成功")
|
||||
else:
|
||||
print(f"[OCR] 百度OCR API获取token失败: {response.text}")
|
||||
except Exception as e:
|
||||
print(f"[OCR] 百度OCR API初始化失败: {e}")
|
||||
|
||||
def recognize(self, image: Image.Image) -> str:
|
||||
if not self.initialized or not self.access_token:
|
||||
return ""
|
||||
|
||||
try:
|
||||
import requests
|
||||
# 将图片转换为base64
|
||||
from io import BytesIO
|
||||
buffer = BytesIO()
|
||||
image.save(buffer, format='PNG')
|
||||
img_base64 = base64.b64encode(buffer.getvalue()).decode()
|
||||
|
||||
# 调用API
|
||||
url = f"https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token={self.access_token}"
|
||||
headers = {"Content-Type": "application/x-www-form-urlencoded"}
|
||||
data = {"image": img_base64}
|
||||
|
||||
response = requests.post(url, headers=headers, data=data, timeout=5)
|
||||
if response.status_code == 200:
|
||||
result = response.json()
|
||||
if "words_result" in result:
|
||||
texts = [item.get("words", "") for item in result["words_result"]]
|
||||
return "".join(texts)
|
||||
return ""
|
||||
except Exception as e:
|
||||
print(f"[OCR] 百度OCR API识别失败: {e}")
|
||||
return ""
|
||||
|
||||
|
||||
class TencentOCRProvider(OCRProvider):
|
||||
"""腾讯OCR API提供者(在线,极快极准)"""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.secret_id = os.environ.get("TENCENT_OCR_SECRET_ID", "")
|
||||
self.secret_key = os.environ.get("TENCENT_OCR_SECRET_KEY", "")
|
||||
|
||||
def initialize(self):
|
||||
if self.initialized:
|
||||
return
|
||||
if not self.secret_id or not self.secret_key:
|
||||
print("[OCR] 腾讯OCR API: 未设置SECRET_ID和SECRET_KEY")
|
||||
print("[OCR] 请设置环境变量: TENCENT_OCR_SECRET_ID 和 TENCENT_OCR_SECRET_KEY")
|
||||
return
|
||||
|
||||
try:
|
||||
from tencentcloud.common import credential
|
||||
from tencentcloud.common.profile.client_profile import ClientProfile
|
||||
from tencentcloud.common.profile.http_profile import HttpProfile
|
||||
from tencentcloud.ocr.v20181119 import ocr_client, models
|
||||
|
||||
cred = credential.Credential(self.secret_id, self.secret_key)
|
||||
httpProfile = HttpProfile()
|
||||
httpProfile.endpoint = "ocr.tencentcloudapi.com"
|
||||
clientProfile = ClientProfile()
|
||||
clientProfile.httpProfile = httpProfile
|
||||
|
||||
self.provider = ocr_client.OcrClient(cred, "ap-beijing", clientProfile)
|
||||
self.models = models
|
||||
self.initialized = True
|
||||
print("[OCR] 腾讯OCR API初始化成功")
|
||||
except Exception as e:
|
||||
print(f"[OCR] 腾讯OCR API初始化失败: {e}")
|
||||
print("[OCR] 请安装: pip install tencentcloud-sdk-python")
|
||||
self.provider = None
|
||||
|
||||
def recognize(self, image: Image.Image) -> str:
|
||||
if not self.initialized or self.provider is None:
|
||||
return ""
|
||||
|
||||
try:
|
||||
# 将图片转换为base64
|
||||
from io import BytesIO
|
||||
buffer = BytesIO()
|
||||
image.save(buffer, format='PNG')
|
||||
img_base64 = base64.b64encode(buffer.getvalue()).decode()
|
||||
|
||||
# 调用API
|
||||
req = self.models.GeneralBasicOCRRequest()
|
||||
req.ImageBase64 = img_base64
|
||||
|
||||
resp = self.provider.GeneralBasicOCR(req)
|
||||
if resp.TextDetections:
|
||||
texts = [item.DetectedText for item in resp.TextDetections]
|
||||
return "".join(texts)
|
||||
return ""
|
||||
except Exception as e:
|
||||
print(f"[OCR] 腾讯OCR API识别失败: {e}")
|
||||
return ""
|
||||
|
||||
|
||||
def get_ocr_provider(ocr_type: Optional[str] = None) -> OCRProvider:
|
||||
"""
|
||||
获取OCR提供者
|
||||
|
||||
Args:
|
||||
ocr_type: OCR类型 ('paddleocr', 'easyocr', 'baidu', 'tencent')
|
||||
如果为None,则从环境变量或config.json读取
|
||||
|
||||
Returns:
|
||||
OCRProvider实例
|
||||
"""
|
||||
if ocr_type is None:
|
||||
# 优先从环境变量读取
|
||||
ocr_type = os.environ.get("OCR_TYPE", "").lower()
|
||||
|
||||
# 如果环境变量未设置,尝试从config.json读取
|
||||
if not ocr_type:
|
||||
try:
|
||||
config_path = os.path.join(os.path.dirname(__file__), "config.json")
|
||||
if os.path.exists(config_path):
|
||||
with open(config_path, 'r', encoding='utf-8') as f:
|
||||
config = json.load(f)
|
||||
ocr_type = config.get("ocr_type", "").lower()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 默认使用paddleocr
|
||||
if not ocr_type:
|
||||
ocr_type = "paddleocr"
|
||||
|
||||
ocr_type = ocr_type.lower()
|
||||
|
||||
if ocr_type == "easyocr":
|
||||
return EasyOCRProvider()
|
||||
elif ocr_type == "baidu":
|
||||
return BaiduOCRProvider()
|
||||
elif ocr_type == "tencent":
|
||||
return TencentOCRProvider()
|
||||
else:
|
||||
return PaddleOCRProvider()
|
||||
|
||||
|
||||
# 全局OCR提供者实例(单例模式)
|
||||
_global_ocr_provider: Optional[OCRProvider] = None
|
||||
|
||||
|
||||
def get_global_ocr_provider() -> OCRProvider:
|
||||
"""获取全局OCR提供者实例(单例)"""
|
||||
global _global_ocr_provider
|
||||
if _global_ocr_provider is None:
|
||||
_global_ocr_provider = get_ocr_provider()
|
||||
_global_ocr_provider.initialize()
|
||||
return _global_ocr_provider
|
||||
|
||||
|
||||
def recognize_image(image_path: str, ocr_type: Optional[str] = None) -> str:
|
||||
"""
|
||||
识别图片中的文字(便捷函数)
|
||||
|
||||
Args:
|
||||
image_path: 图片路径
|
||||
ocr_type: OCR类型(可选)
|
||||
|
||||
Returns:
|
||||
识别到的文字
|
||||
"""
|
||||
try:
|
||||
img = Image.open(image_path)
|
||||
provider = get_global_ocr_provider() if ocr_type is None else get_ocr_provider(ocr_type)
|
||||
if not provider.initialized:
|
||||
provider.initialize()
|
||||
return provider.recognize(img)
|
||||
except Exception as e:
|
||||
print(f"[OCR] 识别失败: {e}")
|
||||
return ""
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 测试代码
|
||||
import sys
|
||||
if len(sys.argv) > 1:
|
||||
image_path = sys.argv[1]
|
||||
ocr_type = sys.argv[2] if len(sys.argv) > 2 else None
|
||||
|
||||
start = time.time()
|
||||
text = recognize_image(image_path, ocr_type)
|
||||
elapsed = (time.time() - start) * 1000
|
||||
|
||||
print(f"识别结果: {text}")
|
||||
print(f"耗时: {elapsed:.0f}ms")
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,187 +0,0 @@
|
||||
"""
|
||||
文件夹整理脚本:整理项目文件夹结构,同时更新代码中的路径引用
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
import re
|
||||
|
||||
# 项目根目录
|
||||
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
# 整理方案:
|
||||
# 1. pic/ 目录分类:
|
||||
# - pic/screenshot.png (保持根目录,运行时临时截图)
|
||||
# - pic/ocr/ (OCR识别用的图片,运行时生成)
|
||||
# - pic/debug/ (调试截图,可归档)
|
||||
# - pic/test/ (测试图片)
|
||||
# - pic/archive/ (归档的旧截图)
|
||||
|
||||
# 运行时必须保持在 pic/ 根目录的文件(不能移动)
|
||||
RUNTIME_FILES = {
|
||||
'screenshot.png', # 当前屏幕截图
|
||||
'cut.png', # 裁剪后的临时图片
|
||||
'window_dump.xml', # UI dump文件
|
||||
}
|
||||
|
||||
# 必须保持的子目录(不能移动)
|
||||
KEEP_DIRS = {
|
||||
'save', # 保存验证图片的目录
|
||||
}
|
||||
|
||||
# OCR识别用的图片(会从根目录移动到 ocr/ 子目录,但代码中已改为从 ocr/ 读取)
|
||||
OCR_FILES = [
|
||||
# 诊断相关
|
||||
'diag_attend_btn.png', '诊断优惠券按钮.png', '诊断优惠券标题.png',
|
||||
'diag_fansclub_join.png', 'diag_follow_title.png', 'diag_guess_like_check.png',
|
||||
'diag_guess_like.png', 'diag_list_title.png', 'diag_live_plaza.png',
|
||||
'diag_recommend_title_check.png', 'diag_recommend_title.png', 'diag_result.png',
|
||||
'诊断购物红包.png', '诊断购物红包按钮.png', 'diag_status.png',
|
||||
# 福袋相关
|
||||
'fudai_content.png', 'fudai_countdown_m.png', 'fudai_countdown_s.png',
|
||||
'fudai_countdown.png', 'fudai_value.png', 'fudai_task_once_1.png',
|
||||
'fudai_task_once_2.png', 'fudai_task_once_3.png', 'fudai_tasks_1.png',
|
||||
'fudai_tasks_2.png', 'fudai_tasks_3.png',
|
||||
# 按钮/界面元素
|
||||
'attend_button.png', '参与按钮.png', '优惠券按钮.png', '优惠券标题.png',
|
||||
'抽奖结果.png', '直播广场.png', '福袋价值.png',
|
||||
'福袋倒计时_分钟.png', '福袋倒计时_秒.png', '福袋倒计时.png',
|
||||
'福袋内容.png', '购物红包.png', '任务用户区域.png',
|
||||
# 直播间相关
|
||||
'live_room_title_large.png', '直播间标题_中.png', 'live_room_title_small.png',
|
||||
'live_room_title.png', 'live_room_title2.png', 'zhibo_follow_list_title.png',
|
||||
'zhibo_follow_list.png', 'zhibo_hongbao.png',
|
||||
'zhibo_status.png', 'zhibo_yanzheng.png',
|
||||
# 其他运行时文件
|
||||
'lucky_draw_result.png', 'no_award_confirm.png', 'bottom_bar.png',
|
||||
'follow_precise_location.png', 'follow_region_precise.png',
|
||||
'follow_tab_detection.png', 'follow_tab_region_detailed.png', 'follow_tab_region.png',
|
||||
'福袋任务_单次_1.png', '福袋任务_单次_2.png',
|
||||
]
|
||||
|
||||
# 测试文件(移动到 test/ 子目录)
|
||||
TEST_FILES = [
|
||||
'test_bottom_tab_follow.png', 'test_bottom_tab.png',
|
||||
'test_bottom_中间区域消息.png', 'test_bottom_关注标签区域.png',
|
||||
'test_bottom_右侧区域我.png', 'test_bottom_完整底部标签栏.png',
|
||||
'test_bottom_左侧区域首页_推荐.png', 'test_follow_title.png',
|
||||
'test_guess_like.png', 'test_list_title.png', 'test_recommend_expanded.png',
|
||||
'test_recommend_title.png',
|
||||
]
|
||||
|
||||
# 调试/归档文件(移动到 archive/ 子目录)
|
||||
DEBUG_DIRS = [
|
||||
'action_fav_roi', 'action_like_roi', 'after_fav_click', 'after_like_click',
|
||||
'after_swipe', 'before_detect_action_fav_roi', 'before_detect_action_like_roi',
|
||||
'before_fav_click', 'before_like_click', 'before_swipe',
|
||||
'comment_after_close', 'comment_after_focus', 'comment_after_input',
|
||||
'comment_after_open', 'comment_after_send', 'comment_before_open',
|
||||
'desktop_icon', 'start', 'step1_close', 'step2_back', 'step3_browse_done',
|
||||
'step4_live', 'step5_enter',
|
||||
]
|
||||
|
||||
DEBUG_FILES = [
|
||||
'screenshot_annotated.png', 'screenshot_regions_marked.png',
|
||||
'screenshot_直播广场_标注.png',
|
||||
]
|
||||
|
||||
|
||||
def organize_pic_directory():
|
||||
"""整理 pic 目录"""
|
||||
pic_dir = os.path.join(PROJECT_ROOT, 'pic')
|
||||
if not os.path.exists(pic_dir):
|
||||
print(f"[整理] pic 目录不存在,跳过")
|
||||
return
|
||||
|
||||
# 创建子目录
|
||||
ocr_dir = os.path.join(pic_dir, 'ocr')
|
||||
test_dir = os.path.join(pic_dir, 'test')
|
||||
archive_dir = os.path.join(pic_dir, 'archive')
|
||||
|
||||
for d in [ocr_dir, test_dir, archive_dir]:
|
||||
os.makedirs(d, exist_ok=True)
|
||||
|
||||
# 移动 OCR 文件
|
||||
moved_ocr = 0
|
||||
for filename in OCR_FILES:
|
||||
src = os.path.join(pic_dir, filename)
|
||||
if os.path.exists(src):
|
||||
dst = os.path.join(ocr_dir, filename)
|
||||
if not os.path.exists(dst):
|
||||
shutil.move(src, dst)
|
||||
moved_ocr += 1
|
||||
print(f"[整理] 移动 OCR 文件: {filename} -> ocr/{filename}")
|
||||
|
||||
# 移动测试文件
|
||||
moved_test = 0
|
||||
for filename in TEST_FILES:
|
||||
src = os.path.join(pic_dir, filename)
|
||||
if os.path.exists(src):
|
||||
dst = os.path.join(test_dir, filename)
|
||||
if not os.path.exists(dst):
|
||||
shutil.move(src, dst)
|
||||
moved_test += 1
|
||||
print(f"[整理] 移动测试文件: {filename} -> test/{filename}")
|
||||
|
||||
# 移动调试目录(跳过需要保留的目录)
|
||||
moved_dirs = 0
|
||||
for dirname in DEBUG_DIRS:
|
||||
if dirname in KEEP_DIRS:
|
||||
continue # 跳过需要保留的目录
|
||||
src = os.path.join(pic_dir, dirname)
|
||||
if os.path.exists(src) and os.path.isdir(src):
|
||||
dst = os.path.join(archive_dir, dirname)
|
||||
if not os.path.exists(dst):
|
||||
shutil.move(src, dst)
|
||||
moved_dirs += 1
|
||||
print(f"[整理] 移动调试目录: {dirname}/ -> archive/{dirname}/")
|
||||
|
||||
# 移动调试文件
|
||||
moved_debug = 0
|
||||
for filename in DEBUG_FILES:
|
||||
src = os.path.join(pic_dir, filename)
|
||||
if os.path.exists(src):
|
||||
dst = os.path.join(archive_dir, filename)
|
||||
if not os.path.exists(dst):
|
||||
shutil.move(src, dst)
|
||||
moved_debug += 1
|
||||
print(f"[整理] 移动调试文件: {filename} -> archive/{filename}")
|
||||
|
||||
print(f"\n[整理完成] pic 目录整理统计:")
|
||||
print(f" - OCR 文件: {moved_ocr} 个 -> pic/ocr/")
|
||||
print(f" - 测试文件: {moved_test} 个 -> pic/test/")
|
||||
print(f" - 调试目录: {moved_dirs} 个 -> pic/archive/")
|
||||
print(f" - 调试文件: {moved_debug} 个 -> pic/archive/")
|
||||
print(f"\n[提示] 代码已更新,支持新旧路径查找(向后兼容)")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import sys
|
||||
print("=" * 60)
|
||||
print("文件夹整理脚本")
|
||||
print("=" * 60)
|
||||
print("\n此脚本将:")
|
||||
print(" 1. 整理 pic/ 目录,将文件分类到子目录")
|
||||
print(" 2. OCR文件 -> pic/ocr/")
|
||||
print(" 3. 测试文件 -> pic/test/")
|
||||
print(" 4. 调试文件/目录 -> pic/archive/")
|
||||
print("\n运行时文件(screenshot.png, cut.png)保持在根目录")
|
||||
print("\n[提示] 代码已更新,支持新旧路径查找(向后兼容)")
|
||||
print("=" * 60)
|
||||
|
||||
# 支持命令行参数 --yes 自动确认
|
||||
auto_confirm = '--yes' in sys.argv or '-y' in sys.argv
|
||||
|
||||
if not auto_confirm:
|
||||
try:
|
||||
response = input("\n是否继续?(y/n): ").strip().lower()
|
||||
except (EOFError, KeyboardInterrupt):
|
||||
print("\n已取消(非交互式环境,使用 --yes 参数可自动确认)")
|
||||
sys.exit(0)
|
||||
else:
|
||||
response = 'y'
|
||||
|
||||
if response == 'y':
|
||||
organize_pic_directory()
|
||||
else:
|
||||
print("已取消")
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
测试关注标签坐标功能
|
||||
用于验证关注标签坐标 (712, 169) 是否正确配置
|
||||
"""
|
||||
|
||||
import re
|
||||
import os
|
||||
|
||||
def test_coordinates():
|
||||
"""测试关注标签坐标是否正确配置"""
|
||||
script_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
douyin_fudai_path = os.path.join(script_dir, "douyin_fudai.py")
|
||||
|
||||
if not os.path.exists(douyin_fudai_path):
|
||||
print("错误: 未找到 douyin_fudai.py 文件")
|
||||
return False
|
||||
|
||||
with open(douyin_fudai_path, "r", encoding="utf-8") as f:
|
||||
content = f.read()
|
||||
|
||||
# 检查坐标定义
|
||||
x_match = re.search(r'self\.yanghao_follow_tab_x\s*=\s*(\d+)', content)
|
||||
y_match = re.search(r'self\.yanghao_follow_tab_y\s*=\s*(\d+)', content)
|
||||
|
||||
if not x_match or not y_match:
|
||||
print("错误: 未找到关注标签坐标定义")
|
||||
return False
|
||||
|
||||
x_coord = int(x_match.group(1))
|
||||
y_coord = int(y_match.group(1))
|
||||
|
||||
print("=" * 50)
|
||||
print("关注标签坐标测试")
|
||||
print("=" * 50)
|
||||
print(f"当前配置的坐标: ({x_coord}, {y_coord})")
|
||||
print(f"预期坐标: (712, 169)")
|
||||
|
||||
if x_coord == 712 and y_coord == 169:
|
||||
print("\n[OK] 坐标配置正确!")
|
||||
|
||||
# 检查坐标使用位置
|
||||
usage_pattern = r'follow_tab_x\s*=\s*int\(getattr\(self,\s*"yanghao_follow_tab_x"'
|
||||
if re.search(usage_pattern, content):
|
||||
print("[OK] 坐标在使用位置正确获取")
|
||||
else:
|
||||
print("[WARN] 警告: 未找到坐标使用代码")
|
||||
|
||||
# 检查日志输出
|
||||
log_pattern = r'检测到推荐页面,点击关注标签 ->'
|
||||
if re.search(log_pattern, content):
|
||||
print("[OK] 日志输出代码存在")
|
||||
|
||||
print("\n测试通过!")
|
||||
print("\n下一步:")
|
||||
print("1. 运行脚本,观察日志中是否显示: 检测到推荐页面,点击关注标签 -> (712, 169)")
|
||||
print("2. 验证点击位置是否准确落在关注标签上")
|
||||
print("3. 如果点击位置不准确,可以微调坐标值")
|
||||
|
||||
return True
|
||||
else:
|
||||
print(f"\n[ERROR] 坐标配置不匹配!")
|
||||
print(f" 当前: ({x_coord}, {y_coord})")
|
||||
print(f" 预期: (712, 169)")
|
||||
return False
|
||||
|
||||
if __name__ == "__main__":
|
||||
success = test_coordinates()
|
||||
exit(0 if success else 1)
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
"""
|
||||
简单的图片坐标查看工具
|
||||
直接查看现有的 OCR 截图文件,帮助你确认坐标
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from PIL import Image
|
||||
|
||||
# 修复 Windows 控制台编码问题
|
||||
if sys.platform == 'win32':
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding='utf-8', errors='replace') # type: ignore[attr-defined]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def show_image_info(image_path):
|
||||
"""显示图片信息和简单的坐标提示"""
|
||||
if not os.path.exists(image_path):
|
||||
print(f"❌ 图片文件不存在: {image_path}")
|
||||
return False
|
||||
|
||||
try:
|
||||
img = Image.open(image_path)
|
||||
width, height = img.size
|
||||
file_size = os.path.getsize(image_path) / 1024 # KB
|
||||
|
||||
print(f"\n{'='*60}")
|
||||
print(f"图片信息: {os.path.basename(image_path)}")
|
||||
print(f"{'='*60}")
|
||||
print(f"📐 尺寸: {width} x {height} 像素")
|
||||
print(f"📦 文件大小: {file_size:.2f} KB")
|
||||
print(f"📍 路径: {image_path}")
|
||||
print(f"\n💡 如何获取坐标:")
|
||||
print(f" 方法1: Windows画图工具(推荐)")
|
||||
print(f" 1. 双击图片文件,用画图打开")
|
||||
print(f" 2. 将鼠标移动到目标位置")
|
||||
print(f" 3. 查看画图左下角状态栏,显示格式: 'X: 123 Y: 456'")
|
||||
print(f" 4. 记录左上角坐标 (x1, y1) 和右下角坐标 (x2, y2)")
|
||||
print(f"\n 方法2: 使用截图工具")
|
||||
print(f" 1. 打开 QQ截图 / 微信截图 / Snipping Tool")
|
||||
print(f" 2. 框选目标区域")
|
||||
print(f" 3. 查看显示的区域大小和位置")
|
||||
print(f"\n 方法3: 使用交互式查看器(需要 tkinter)")
|
||||
print(f" 运行: python check_image_coordinates.py interactive")
|
||||
print(f"\n📝 坐标格式说明:")
|
||||
print(f" - 坐标系: 左上角为原点 (0, 0)")
|
||||
print(f" - X轴: 向右递增")
|
||||
print(f" - Y轴: 向下递增")
|
||||
print(f" - 格式: cut_pic(x1, y1, x2, y2, ...)")
|
||||
print(f" - 示例: cut_pic(100, 150, 400, 200, ...) 表示")
|
||||
print(f" 左上角(100, 150) 到 右下角(400, 200) 的矩形区域")
|
||||
print(f"{'='*60}\n")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"❌ 打开图片失败: {e}")
|
||||
return False
|
||||
|
||||
if __name__ == "__main__":
|
||||
base_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
# 查看多个可能的图片
|
||||
images_to_check = [
|
||||
('当前截图', os.path.join(base_dir, 'pic', 'screenshot.png')),
|
||||
('直播间标题_中', os.path.join(base_dir, 'pic', 'ocr', '直播间标题_中.png')),
|
||||
('直播间标题(large)', os.path.join(base_dir, 'pic', 'ocr', 'live_room_title_large.png')),
|
||||
('直播间标题(small)', os.path.join(base_dir, 'pic', 'ocr', 'live_room_title_small.png')),
|
||||
]
|
||||
|
||||
print("🔍 直播间标题坐标查看工具\n")
|
||||
|
||||
# 只显示存在的图片
|
||||
found_images = []
|
||||
for name, path in images_to_check:
|
||||
if os.path.exists(path):
|
||||
found_images.append((name, path))
|
||||
|
||||
if not found_images:
|
||||
print("❌ 没有找到任何图片文件")
|
||||
print(f" 请确保程序已运行过,生成了截图文件")
|
||||
else:
|
||||
for name, path in found_images:
|
||||
show_image_info(path)
|
||||
|
||||
Reference in new issue
Block a user