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:
Your Name committed 2025-12-28 14:16:40 +08:00
1 parent ea7159355b
commit c67f22f76f
139 files changed
+7571 -7828

No files matched your search

+179
View File
@@ -0,0 +1,179 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""检查项目依赖库的安装状态"""
import sys
import io
# 设置UTF-8输出
if sys.platform == 'win32':
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
dependencies = {
'PIL': ('Pillow', 'Image Processing'),
'cv2': ('opencv-python', 'Computer Vision'),
'numpy': ('numpy', 'Numerical Computing'),
'paddleocr': ('paddleocr', 'OCR Recognition'),
'paddlepaddle': ('paddlepaddle', 'Deep Learning'),
'ttkbootstrap': ('ttkbootstrap', 'GUI Framework'),
'easyocr': ('easyocr', 'OCR Recognition (Optional)'),
}
print("=" * 60)
print("Dependency Check Report")
print("=" * 60)
print(f"Python Version: {sys.version}\n")
missing = []
installed = []
optional_missing = []
for module_name, (package_name, description) in dependencies.items():
try:
__import__(module_name)
print(f"[OK] {package_name:20s} ({description:25s}) - Installed")
installed.append(package_name)
except ImportError:
if module_name == 'easyocr':
print(f"[OPT] {package_name:20s} ({description:25s}) - Not Installed (Optional)")
optional_missing.append(package_name)
else:
print(f"[MISS] {package_name:20s} ({description:25s}) - Not Installed")
missing.append(package_name)
except Exception as e:
print(f"[ERR] {package_name:20s} - Error: {e}")
print("\n" + "=" * 60)
print("Summary")
print("=" * 60)
print(f"Installed: {len(installed)}/{len(dependencies)}")
if missing:
print(f"\nMissing Required Dependencies ({len(missing)}):")
for pkg in missing:
print(f" - {pkg}")
if optional_missing:
print(f"\nMissing Optional Dependencies ({len(optional_missing)}):")
for pkg in optional_missing:
print(f" - {pkg}")
if missing:
print("\nInstall Command:")
print(f"pip install {' '.join(missing)}")
print("\nOr use:")
print(" pip install -r requirements.txt")
sys.exit(1)
else:
print("\n[SUCCESS] All required dependencies are installed!")
sys.exit(0)
+196
View File
@@ -0,0 +1,196 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
检查GPU是否可用的脚本
"""
import sys
# 修复Windows控制台编码问题
if sys.platform == "win32":
try:
sys.stdout.reconfigure(encoding="utf-8") # type: ignore[attr-defined]
except Exception:
pass
def check_torch_cuda():
"""检查PyTorch是否支持CUDA"""
try:
import torch # type: ignore
if torch.cuda.is_available():
print(f"[GPU检测] PyTorch CUDA可用")
print(f" CUDA版本: {torch.version.cuda}")
print(f" GPU数量: {torch.cuda.device_count()}")
for i in range(torch.cuda.device_count()):
print(f" GPU {i}: {torch.cuda.get_device_name(i)}")
return True
else:
print("[GPU检测] PyTorch CUDA不可用")
return False
except ImportError:
print("[GPU检测] PyTorch未安装")
return False
except Exception as e:
print(f"[GPU检测] PyTorch CUDA检测失败: {e}")
return False
def check_easyocr_gpu():
"""检查EasyOCR是否可以使用GPU"""
try:
import easyocr # type: ignore
print("[GPU检测] EasyOCR已安装")
# EasyOCR使用PyTorch,所以需要PyTorch支持CUDA
try:
import torch # type: ignore
if torch.cuda.is_available():
print("[GPU检测] EasyOCR可以使用GPU(通过PyTorch CUDA)")
return True
else:
print("[GPU检测] EasyOCR无法使用GPU(PyTorch CUDA不可用)")
return False
except ImportError:
print("[GPU检测] EasyOCR需要PyTorch才能使用GPU")
return False
except ImportError:
print("[GPU检测] EasyOCR未安装")
return False
except Exception as e:
print(f"[GPU检测] EasyOCR GPU检测失败: {e}")
return False
def check_paddleocr_gpu():
"""检查PaddleOCR是否可以使用GPU"""
try:
from paddleocr import PaddleOCR
print("[GPU检测] PaddleOCR已安装")
# PaddleOCR需要paddlepaddle-gpu版本
try:
import paddle
if paddle.device.is_compiled_with_cuda():
print("[GPU检测] PaddleOCR可以使用GPU(paddlepaddle-gpu已安装)")
if paddle.device.get_device():
print(f" Paddle设备: {paddle.device.get_device()}")
return True
else:
print("[GPU检测] PaddleOCR无法使用GPU(需要安装paddlepaddle-gpu)")
return False
except ImportError:
print("[GPU检测] PaddleOCR需要paddlepaddle才能使用GPU")
return False
except ImportError:
print("[GPU检测] PaddleOCR未安装")
return False
except Exception as e:
print(f"[GPU检测] PaddleOCR GPU检测失败: {e}")
return False
def check_integrated_graphics():
"""检查是否是集成显卡(核显)"""
try:
import torch # type: ignore
if torch.cuda.is_available():
for i in range(torch.cuda.device_count()):
gpu_name = torch.cuda.get_device_name(i).lower()
# 常见的核显标识
integrated_keywords = [
"intel",
"iris",
"uhd",
"hd graphics",
"amd",
"radeon vega",
"radeon graphics",
]
is_integrated = any(
keyword in gpu_name for keyword in integrated_keywords
)
if is_integrated:
print(
f"[GPU检测] 检测到可能是集成显卡: {torch.cuda.get_device_name(i)}"
)
print("[GPU检测] 警告:集成显卡的GPU加速效果可能不明显")
return True
except Exception:
pass
return False
def main():
"""主函数"""
print("=" * 60)
print("GPU可用性检测")
print("=" * 60)
print()
# 检查PyTorch CUDA
print("[1] 检查PyTorch CUDA支持")
torch_cuda_available = check_torch_cuda()
print()
# 检查是否是核显
is_integrated = False # 初始化,避免未绑定错误
if torch_cuda_available:
print("[2] 检查显卡类型")
is_integrated = check_integrated_graphics()
print()
# 检查EasyOCR GPU支持
print("[3] 检查EasyOCR GPU支持")
easyocr_gpu_available = check_easyocr_gpu()
print()
# 检查PaddleOCR GPU支持
print("[4] 检查PaddleOCR GPU支持")
paddleocr_gpu_available = check_paddleocr_gpu()
print()
# 总结
print("=" * 60)
print("检测结果总结")
print("=" * 60)
if torch_cuda_available:
print("[OK] PyTorch CUDA可用")
if is_integrated:
print("[WARN] 检测到集成显卡,GPU加速效果可能有限")
else:
print("[OK] 检测到独立显卡,GPU加速效果较好")
else:
print("[NO] PyTorch CUDA不可用(将使用CPU模式)")
if easyocr_gpu_available:
print("[OK] EasyOCR可以使用GPU")
else:
print("[NO] EasyOCR无法使用GPU(将使用CPU模式)")
if paddleocr_gpu_available:
print("[OK] PaddleOCR可以使用GPU")
else:
print("[NO] PaddleOCR无法使用GPU(将使用CPU模式)")
print()
print("建议:")
if not torch_cuda_available:
print(" - 如果使用NVIDIA独立显卡,请安装CUDA和PyTorch GPU版本")
print(" - 如果使用集成显卡,GPU加速效果可能不明显,建议继续使用CPU模式")
elif is_integrated:
print(" - 集成显卡的GPU加速效果可能不明显")
print(" - 可以尝试启用GPU,但性能提升可能有限")
print(" - 如果遇到问题,建议继续使用CPU模式")
else:
print(" - 可以启用GPU加速以提升OCR性能")
print(" - 修改 Underlying_Operations.py 中的 gpu=False 为 gpu=True")
if __name__ == "__main__":
main()
+159
View File
@@ -0,0 +1,159 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
检查GUI参数设置冲突的脚本
"""
import json
import os
import sys
# 修复Windows控制台编码问题
if sys.platform == "win32":
try:
sys.stdout.reconfigure(encoding='utf-8') # type: ignore[attr-defined]
except Exception:
pass
CONFIG_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "config", "config.json")
def check_conflicts(cfg: dict) -> list:
"""检查配置参数冲突,返回冲突列表"""
conflicts = []
# 1. 检查倒计时参数冲突
skip_gt = int(cfg.get("skip_if_countdown_gt_seconds", 900) or 900)
skip_lt = int(cfg.get("skip_if_countdown_lt_seconds", 5) or 5)
join_ahead = int(cfg.get("high_value_fudai_join_ahead_seconds", 120) or 120)
if skip_lt >= skip_gt:
conflicts.append({
"type": "倒计时阈值冲突",
"message": f"倒计时小于阈值({skip_lt}秒) >= 倒计时大于阈值({skip_gt}秒),这会导致所有福袋都被过滤",
"params": {
"skip_if_countdown_lt_seconds": skip_lt,
"skip_if_countdown_gt_seconds": skip_gt,
}
})
if join_ahead > skip_gt:
conflicts.append({
"type": "预约参与阈值冲突",
"message": f"预约参与阈值({join_ahead}秒) > 倒计时大于阈值({skip_gt}秒),高价值福袋即使剩余时间在预约阈值内也会被过滤",
"params": {
"high_value_fudai_join_ahead_seconds": join_ahead,
"skip_if_countdown_gt_seconds": skip_gt,
}
})
if join_ahead < skip_lt:
conflicts.append({
"type": "预约参与阈值冲突",
"message": f"预约参与阈值({join_ahead}秒) < 倒计时小于阈值({skip_lt}秒),可能导致高价值福袋在预约阈值内也被过滤",
"params": {
"high_value_fudai_join_ahead_seconds": join_ahead,
"skip_if_countdown_lt_seconds": skip_lt,
}
})
# 2. 检查参与人数参数冲突
min_participants = int(cfg.get("min_participants", 0) or 0)
max_participants = int(cfg.get("max_participants", 0) or 0)
if max_participants > 0 and min_participants > max_participants:
conflicts.append({
"type": "参与人数阈值冲突",
"message": f"最小参与人数({min_participants}) > 最大参与人数({max_participants}),这会导致所有福袋都被过滤",
"params": {
"min_participants": min_participants,
"max_participants": max_participants,
}
})
# 3. 检查价值参数冲突
min_value = float(cfg.get("min_prize_value_yuan", 0) or 0)
high_value_threshold = float(cfg.get("high_value_fudai_threshold_yuan", 1000) or 1000)
if high_value_threshold < min_value:
conflicts.append({
"type": "价值阈值冲突",
"message": f"高价值阈值({high_value_threshold}元) < 最小价值({min_value}元),高价值福袋可能被最小价值过滤掉",
"params": {
"high_value_fudai_threshold_yuan": high_value_threshold,
"min_prize_value_yuan": min_value,
}
})
# 4. 检查高价值预约相关参数
high_value_enabled = bool(cfg.get("high_value_fudai_enabled", False))
if high_value_enabled and high_value_threshold <= 0:
conflicts.append({
"type": "高价值预约配置错误",
"message": f"已启用高价值预约,但高价值阈值({high_value_threshold}元) <= 0,预约功能无法正常工作",
"params": {
"high_value_fudai_enabled": high_value_enabled,
"high_value_fudai_threshold_yuan": high_value_threshold,
}
})
# 5. 检查预约相关参数合理性
if high_value_enabled:
max_reservations = int(cfg.get("high_value_fudai_max_reservations", 5) or 5)
if max_reservations <= 0:
conflicts.append({
"type": "预约数量配置错误",
"message": f"最多记录数量({max_reservations}) <= 0,预约功能无法正常工作",
"params": {
"high_value_fudai_max_reservations": max_reservations,
}
})
# 6. 检查福袋查找相关参数
fudai_icon_max_wait = float(cfg.get("fudai_icon_max_wait_seconds", 5.0) or 5.0)
fudai_icon_retry_delay = float(cfg.get("fudai_icon_retry_delay_seconds", 0.6) or 0.6)
if fudai_icon_max_wait < fudai_icon_retry_delay:
conflicts.append({
"type": "福袋查找参数不合理",
"message": f"最大等待时间({fudai_icon_max_wait}秒) < 重试延迟({fudai_icon_retry_delay}秒),可能导致只检测一次就放弃",
"params": {
"fudai_icon_max_wait_seconds": fudai_icon_max_wait,
"fudai_icon_retry_delay_seconds": fudai_icon_retry_delay,
}
})
return conflicts
def main():
"""主函数"""
if not os.path.exists(CONFIG_PATH):
print(f"配置文件不存在: {CONFIG_PATH}")
return
try:
with open(CONFIG_PATH, "r", encoding="utf-8") as f:
cfg = json.load(f)
except Exception as e:
print(f"读取配置文件失败: {e}")
return
conflicts = check_conflicts(cfg)
if not conflicts:
print("[OK] 未发现参数冲突")
return
print(f"发现 {len(conflicts)} 个参数冲突:\n")
for i, conflict in enumerate(conflicts, 1):
print(f"{i}. 【{conflict['type']}】")
print(f" {conflict['message']}")
print(f" 相关参数: {conflict['params']}")
print()
if __name__ == "__main__":
main()
+414
View File
@@ -0,0 +1,414 @@
"""
项目无用文件清理脚本
==================
功能:
1. 识别并分类无用文件(缓存、临时文件、旧日志等)
2. 安全删除(带备份和异常处理)
3. 生成清理报告
"""
import os
import shutil
import time
from pathlib import Path
from typing import List, Dict, Tuple
from datetime import datetime, timedelta
class ProjectCleaner:
"""项目清理器"""
def __init__(self, project_root: str = "."):
self.project_root = Path(project_root).resolve()
self.deleted_files: List[str] = []
self.deleted_dirs: List[str] = []
self.failed_deletes: List[Tuple[str, str]] = []
self.total_size_freed = 0
def get_file_size(self, path: Path) -> int:
"""获取文件或目录大小(字节)"""
try:
if path.is_file():
return path.stat().st_size
elif path.is_dir():
total = 0
for item in path.rglob("*"):
if item.is_file():
try:
total += item.stat().st_size
except (OSError, PermissionError):
pass
return total
except (OSError, PermissionError):
pass
return 0
def safe_delete_file(self, file_path: Path) -> bool:
"""安全删除文件"""
try:
if file_path.exists() and file_path.is_file():
size = self.get_file_size(file_path)
file_path.unlink()
self.deleted_files.append(str(file_path))
self.total_size_freed += size
return True
except PermissionError as e:
self.failed_deletes.append((str(file_path), f"权限错误: {e}"))
except Exception as e:
self.failed_deletes.append((str(file_path), f"错误: {e}"))
return False
def safe_delete_dir(self, dir_path: Path) -> bool:
"""安全删除目录"""
try:
if dir_path.exists() and dir_path.is_dir():
size = self.get_file_size(dir_path)
shutil.rmtree(dir_path)
self.deleted_dirs.append(str(dir_path))
self.total_size_freed += size
return True
except PermissionError as e:
self.failed_deletes.append((str(dir_path), f"权限错误: {e}"))
except Exception as e:
self.failed_deletes.append((str(dir_path), f"错误: {e}"))
return False
def _should_exclude(self, path: Path) -> bool:
"""判断路径是否应该被排除"""
# 排除虚拟环境目录
exclude_patterns = [
".venv",
"venv",
"env",
".env",
"node_modules",
".git",
".vscode",
".idea",
]
path_str = str(path)
for pattern in exclude_patterns:
if pattern in path_str:
return True
return False
def find_python_cache(self) -> List[Path]:
"""查找Python缓存文件"""
cache_files = []
# __pycache__ 目录
for cache_dir in self.project_root.rglob("__pycache__"):
if cache_dir.is_dir() and not self._should_exclude(cache_dir):
cache_files.append(cache_dir)
# .pyc 文件
for pyc_file in self.project_root.rglob("*.pyc"):
if pyc_file.is_file() and not self._should_exclude(pyc_file):
cache_files.append(pyc_file)
# .pyo 文件
for pyo_file in self.project_root.rglob("*.pyo"):
if pyo_file.is_file() and not self._should_exclude(pyo_file):
cache_files.append(pyo_file)
return cache_files
def find_temp_files(self) -> List[Path]:
"""查找临时文件"""
temp_patterns = [
"*.tmp",
"*.temp",
"*.bak",
"*.swp",
"*.swo",
"*~",
".DS_Store",
"Thumbs.db",
"desktop.ini",
]
temp_files = []
for pattern in temp_patterns:
for temp_file in self.project_root.rglob(pattern):
if temp_file.is_file() and not self._should_exclude(temp_file):
temp_files.append(temp_file)
return temp_files
def find_old_logs(self, keep_days: int = 7) -> List[Path]:
"""查找旧日志文件(保留最近N天)"""
log_files = []
cutoff_time = time.time() - (keep_days * 24 * 60 * 60)
for log_file in self.project_root.rglob("*.log"):
if log_file.is_file() and not self._should_exclude(log_file):
try:
# 保留最近的日志文件
if log_file.stat().st_mtime < cutoff_time:
log_files.append(log_file)
except (OSError, PermissionError):
pass
return log_files
def find_report_files(self) -> List[Path]:
"""查找代码分析报告文件"""
report_patterns = [
"pylint_report.txt",
"pyright_report.txt",
"*.report",
"*.lint",
]
report_files = []
for pattern in report_patterns:
for report_file in self.project_root.rglob(pattern):
if report_file.is_file() and not self._should_exclude(report_file):
report_files.append(report_file)
return report_files
def find_unused_dirs(self) -> List[Path]:
"""查找可能无用的目录"""
unused_dirs = []
# 检查原始代码目录(如果确认不再需要)
legacy_dir = self.project_root / "原始代码"
if legacy_dir.exists() and legacy_dir.is_dir():
# 检查是否被引用
unused_dirs.append(legacy_dir)
# tools/legacy 目录(旧工具,可能不再使用)
legacy_tools_dir = self.project_root / "tools" / "legacy"
if legacy_tools_dir.exists() and legacy_tools_dir.is_dir():
unused_dirs.append(legacy_tools_dir)
return unused_dirs
def find_dummy_files(self) -> List[Path]:
"""查找测试/占位文件"""
dummy_files = []
# 查找名为 dummy 的文件
dummy_file = self.project_root / "dummy"
if dummy_file.exists():
dummy_files.append(dummy_file)
return dummy_files
def cleanup(self, dry_run: bool = True) -> Dict:
"""执行清理
参数:
dry_run: 是否只是预览(不实际删除)
返回:
清理报告
"""
print(f"{'预览模式' if dry_run else '执行清理'}:扫描项目目录...")
print(f"项目根目录: {self.project_root}")
print("-" * 60)
# 1. Python缓存
print("\n1. Python缓存文件:")
cache_files = self.find_python_cache()
for cache_file in cache_files:
size = self.get_file_size(cache_file)
print(f" - {cache_file.relative_to(self.project_root)} ({self._format_size(size)})")
if not dry_run:
if cache_file.is_file():
self.safe_delete_file(cache_file)
else:
self.safe_delete_dir(cache_file)
# 2. 临时文件
print("\n2. 临时文件:")
temp_files = self.find_temp_files()
for temp_file in temp_files:
size = self.get_file_size(temp_file)
print(f" - {temp_file.relative_to(self.project_root)} ({self._format_size(size)})")
if not dry_run:
self.safe_delete_file(temp_file)
# 3. 旧日志文件(保留最近7天)
print("\n3. 旧日志文件(保留最近7天):")
old_logs = self.find_old_logs(keep_days=7)
for log_file in old_logs:
size = self.get_file_size(log_file)
mtime = datetime.fromtimestamp(log_file.stat().st_mtime)
print(f" - {log_file.relative_to(self.project_root)} ({self._format_size(size)}, {mtime.strftime('%Y-%m-%d')})")
if not dry_run:
self.safe_delete_file(log_file)
# 4. 代码分析报告
print("\n4. 代码分析报告文件:")
report_files = self.find_report_files()
for report_file in report_files:
size = self.get_file_size(report_file)
print(f" - {report_file.relative_to(self.project_root)} ({self._format_size(size)})")
if not dry_run:
self.safe_delete_file(report_file)
# 5. 可能无用的目录(需要确认)
print("\n5. 可能无用的目录(需要确认):")
unused_dirs = self.find_unused_dirs()
for unused_dir in unused_dirs:
size = self.get_file_size(unused_dir)
print(f" - {unused_dir.relative_to(self.project_root)} ({self._format_size(size)})")
print(f" 警告:此目录可能包含重要代码,请确认后再删除")
if not dry_run:
# 默认不删除,需要用户确认
pass
# 6. 测试/占位文件
print("\n6. 测试/占位文件:")
dummy_files = self.find_dummy_files()
for dummy_file in dummy_files:
size = self.get_file_size(dummy_file)
print(f" - {dummy_file.relative_to(self.project_root)} ({self._format_size(size)})")
if not dry_run:
self.safe_delete_file(dummy_file)
# 生成报告
report = {
"dry_run": dry_run,
"deleted_files": len(self.deleted_files),
"deleted_dirs": len(self.deleted_dirs),
"failed_deletes": len(self.failed_deletes),
"total_size_freed": self.total_size_freed,
"cache_files": len(cache_files),
"temp_files": len(temp_files),
"old_logs": len(old_logs),
"report_files": len(report_files),
"unused_dirs": len(unused_dirs),
"dummy_files": len(dummy_files),
}
return report
def _format_size(self, size_bytes: int) -> str:
"""格式化文件大小"""
size = float(size_bytes)
for unit in ['B', 'KB', 'MB', 'GB']:
if size < 1024.0:
return f"{size:.2f} {unit}"
size /= 1024.0
return f"{size:.2f} TB"
def print_report(self, report: Dict):
"""打印清理报告"""
print("\n" + "=" * 60)
print("清理报告")
print("=" * 60)
print(f"模式: {'预览模式(未实际删除)' if report['dry_run'] else '执行模式(已删除)'}")
print(f"\n扫描结果:")
print(f" - Python缓存文件: {report['cache_files']} 个")
print(f" - 临时文件: {report['temp_files']} 个")
print(f" - 旧日志文件: {report['old_logs']} 个")
print(f" - 代码分析报告: {report['report_files']} 个")
print(f" - 可能无用目录: {report['unused_dirs']} 个")
print(f" - 测试/占位文件: {report['dummy_files']} 个")
if not report['dry_run']:
print(f"\n删除结果:")
print(f" - 已删除文件: {report['deleted_files']} 个")
print(f" - 已删除目录: {report['deleted_dirs']} 个")
print(f" - 释放空间: {self._format_size(report['total_size_freed'])}")
print(f" - 删除失败: {report['failed_deletes']} 个")
if self.failed_deletes:
print(f"\n删除失败的文件:")
for file_path, error in self.failed_deletes:
print(f" - {file_path}: {error}")
def main():
"""主函数"""
import sys
import argparse
parser = argparse.ArgumentParser(description="项目无用文件清理工具")
parser.add_argument(
"--execute",
action="store_true",
help="直接执行清理(不预览)"
)
parser.add_argument(
"--preview-only",
action="store_true",
help="仅预览,不执行清理"
)
args = parser.parse_args()
# 检查是否在项目根目录
if not Path("douyin_guaji.py").exists():
print("错误:请在项目根目录运行此脚本")
sys.exit(1)
cleaner = ProjectCleaner(".")
# 先预览
print("=" * 60)
print("第一步:预览模式(不实际删除)")
print("=" * 60)
preview_report = cleaner.cleanup(dry_run=True)
cleaner.print_report(preview_report)
# 如果只是预览,直接退出
if args.preview_only:
print("\n预览完成,未执行清理操作")
return
# 如果指定了--execute,直接执行
if args.execute:
print("\n" + "=" * 60)
print("第二步:执行清理")
print("=" * 60)
# 重置统计
cleaner.deleted_files = []
cleaner.deleted_dirs = []
cleaner.failed_deletes = []
cleaner.total_size_freed = 0
# 执行清理
final_report = cleaner.cleanup(dry_run=False)
cleaner.print_report(final_report)
print("\n清理完成!")
return
# 否则询问用户(交互式模式)
try:
print("\n" + "=" * 60)
response = input("是否执行清理?(yes/no): ").strip().lower()
if response in ('yes', 'y', '是'):
print("\n" + "=" * 60)
print("第二步:执行清理")
print("=" * 60)
# 重置统计
cleaner.deleted_files = []
cleaner.deleted_dirs = []
cleaner.failed_deletes = []
cleaner.total_size_freed = 0
# 执行清理
final_report = cleaner.cleanup(dry_run=False)
cleaner.print_report(final_report)
print("\n清理完成!")
else:
print("已取消清理操作")
except EOFError:
# 非交互式环境,提示使用命令行参数
print("\n提示:在非交互式环境中,请使用 --execute 参数直接执行清理")
print(" 或使用 --preview-only 参数仅预览")
if __name__ == "__main__":
main()
+83
View File
@@ -0,0 +1,83 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""自动安装缺失的依赖"""
import subprocess
import sys
def install_package(package):
"""安装指定的包"""
try:
print(f"Installing {package}...")
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
print(f"[SUCCESS] {package} installed successfully")
return True
except subprocess.CalledProcessError as e:
print(f"[ERROR] Failed to install {package}: {e}")
return False
def main():
# 检查缺失的依赖
missing = []
try:
import paddlepaddle # type: ignore[import-untyped]
except ImportError:
missing.append("paddlepaddle>=2.5.0,<3.0.0")
try:
import ttkbootstrap
except ImportError:
missing.append("ttkbootstrap>=1.10.0")
if not missing:
print("[SUCCESS] All dependencies are installed!")
return 0
print(f"Missing dependencies: {', '.join(missing)}")
print("\nDo you want to install them? (y/n): ", end='')
# 在非交互环境中自动安装
response = 'y'
try:
response = input().strip().lower()
except (EOFError, KeyboardInterrupt):
response = 'y' # 默认安装
if response in ('y', 'yes', ''):
success_count = 0
for pkg in missing:
if install_package(pkg):
success_count += 1
if success_count == len(missing):
print("\n[SUCCESS] All dependencies installed successfully!")
return 0
else:
print(f"\n[WARNING] {len(missing) - success_count} package(s) failed to install")
print("You may need to install them manually:")
print(f"pip install {' '.join(missing)}")
return 1
else:
print("Installation cancelled.")
return 1
if __name__ == "__main__":
sys.exit(main())
+3 -3
View File
@@ -277,10 +277,10 @@ def _snapshot_context_files(run_root: Path) -> None:
# 一些關鍵單檔:當前配置與入口/主流程
important_files = [
"config.json",
"config/config.json",
"run_cli.py",
"douyin_fudai.py",
"douyin_stage.py",
"douyin/core/douyin_fudai.py",
"douyin/stage/douyin_stage.py",
"douyin_fudai_core.py",
"douyin_reservation.py",
"douyin_robot.py",
+252
View File
@@ -0,0 +1,252 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
生成WPS可导入的流程图SVG文件
使用方法:python 生成WPS流程图.py
"""
import os
import subprocess
import sys
def check_mermaid_cli():
"""检查是否安装了mermaid-cli"""
try:
result = subprocess.run(['mmdc', '--version'],
capture_output=True,
text=True)
return True
except FileNotFoundError:
return False
def install_mermaid_cli():
"""提示用户安装mermaid-cli"""
print("=" * 60)
print("需要安装 mermaid-cli 来生成SVG流程图")
print("=" * 60)
print("\n安装方法:")
print("1. 确保已安装 Node.js (https://nodejs.org/)")
print("2. 运行以下命令安装 mermaid-cli:")
print(" npm install -g @mermaid-js/mermaid-cli")
print("\n或者使用在线工具:")
print("1. 访问 https://mermaid.live/")
print("2. 复制流程图.md中的mermaid代码")
print("3. 点击导出为SVG")
print("=" * 60)
return False
def generate_svg_from_mermaid(mermaid_code, output_file):
"""使用mermaid-cli生成SVG"""
try:
# 创建临时mermaid文件
temp_file = "temp_flowchart.mmd"
with open(temp_file, 'w', encoding='utf-8') as f:
f.write(mermaid_code)
# 使用mmdc生成SVG
result = subprocess.run(
['mmdc', '-i', temp_file, '-o', output_file, '-b', 'transparent'],
capture_output=True,
text=True
)
# 删除临时文件
if os.path.exists(temp_file):
os.remove(temp_file)
if result.returncode == 0:
return True
else:
print(f"生成SVG失败: {result.stderr}")
return False
except Exception as e:
print(f"生成SVG时出错: {e}")
return False
def read_mermaid_from_md():
"""从流程图.md中读取mermaid代码"""
md_file = "流程图.md"
if not os.path.exists(md_file):
print(f"错误: 找不到文件 {md_file}")
return None
with open(md_file, 'r', encoding='utf-8') as f:
content = f.read()
# 提取所有mermaid代码块
mermaid_blocks = []
in_mermaid = False
current_block = []
for line in content.split('\n'):
if line.strip().startswith('```mermaid'):
in_mermaid = True
current_block = []
elif in_mermaid and line.strip() == '```':
in_mermaid = False
if current_block:
mermaid_blocks.append('\n'.join(current_block))
elif in_mermaid:
current_block.append(line)
return mermaid_blocks
def main():
"""主函数"""
print("=" * 60)
print("WPS流程图生成工具")
print("=" * 60)
# 检查mermaid-cli
if not check_mermaid_cli():
install_mermaid_cli()
return
# 读取mermaid代码
print("\n正在读取流程图.md...")
mermaid_blocks = read_mermaid_from_md()
if not mermaid_blocks:
print("错误: 未找到mermaid代码块")
return
print(f"找到 {len(mermaid_blocks)} 个流程图")
# 流程图名称
flowchart_names = [
"主流程图",
"阶段诊断子流程图",
"福袋查找子流程图",
"福袋详情读取子流程图",
"福袋筛选决策子流程图",
"预约处理子流程图",
"异常处理流程"
]
# 生成SVG文件
output_dir = "WPS流程图"
os.makedirs(output_dir, exist_ok=True)
print(f"\n正在生成SVG文件到 {output_dir} 目录...")
for i, mermaid_code in enumerate(mermaid_blocks):
name = flowchart_names[i] if i < len(flowchart_names) else f"流程图{i+1}"
output_file = os.path.join(output_dir, f"{name}.svg")
print(f" 生成: {name}...", end=' ')
if generate_svg_from_mermaid(mermaid_code, output_file):
print("✓ 成功")
else:
print("✗ 失败")
print("\n" + "=" * 60)
print("生成完成!")
print(f"SVG文件保存在: {output_dir}/")
print("\n导入WPS方法:")
print("1. 打开WPS演示(或WPS文字)")
print("2. 插入 → 图片 → 来自文件")
print("3. 选择生成的SVG文件")
print("=" * 60)
if __name__ == "__main__":
main()