Auto commit: 2025-12-21 22:45:00 - Hourly auto save

This commit is contained in:
Your Name committed 2025-12-21 22:45:01 +08:00
1 parent 1a63852bde
commit 5b8dd6e5d4
17 files changed
+1861 -28

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -0,0 +1,38 @@
<!-- Generated by SpecStory, Markdown v2.1.0 -->
<!-- cursor Session 4ca9ef02-abb7-41b0-9356-9e4014cde4d8 (2025-12-21 14:42Z) -->
# 让git每一小时保存一次我的修改,并提交和推送我的代码到github (2025-12-21 14:42Z)
_**User (2025-12-21 14:42Z)**_
让git每一小时保存一次我的修改,并提交和推送我的代码到github
---
_**Agent (model default, mode Agent)**_
---
---
_**User (2025-12-21 14:42Z)**_
让git每一小时保存一次我的修改,并提交和推送我的代码到github
---
_**Agent (model default, mode Agent)**_
---
---
+2
View File
@@ -162,3 +162,5 @@ python check_dependencies.py
3. 考虑使用虚拟环境隔离依赖 3. 考虑使用虚拟环境隔离依赖
4. 定期检查依赖的安全更新 4. 定期检查依赖的安全更新
+2
View File
@@ -141,3 +141,5 @@ douyin_guaji
└── ttkbootstrap (可选, GUI美化) └── ttkbootstrap (可选, GUI美化)
``` ```
+2
View File
@@ -82,3 +82,5 @@
2. **类型注解**: 可以为更多函数添加类型注解以提高代码可读性 2. **类型注解**: 可以为更多函数添加类型注解以提高代码可读性
3. **测试**: 建议添加单元测试以确保修复的有效性 3. **测试**: 建议添加单元测试以确保修复的有效性
+11
View File
@@ -0,0 +1,11 @@
@echo off
REM Git自动提交和推送批处理脚本
REM 每小时自动保存修改、提交并推送到GitHub
cd /d "C:\Users\12742\Desktop\douyin_guaji-main"
REM 运行PowerShell脚本
powershell.exe -ExecutionPolicy Bypass -File "%~dp0auto_commit_push.ps1"
pause
+52
View File
@@ -0,0 +1,52 @@
# Git Auto Commit and Push Script
# Auto save, commit and push to GitHub every hour
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$ErrorActionPreference = "Stop"
# Switch to project directory
$projectPath = "C:\Users\12742\Desktop\douyin_guaji-main"
Set-Location $projectPath
# Get current timestamp
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Auto Commit Script Running: $timestamp" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
try {
# Check for changes
$status = git status --porcelain
if ($status) {
Write-Host "Changes detected, starting commit..." -ForegroundColor Yellow
# Add all modified files
git add -A
# Create commit message with timestamp
$commitMessage = "Auto commit: $timestamp - Hourly auto save"
git commit -m $commitMessage
Write-Host "Commit successful: $commitMessage" -ForegroundColor Green
# Push to GitHub
Write-Host "Pushing to GitHub..." -ForegroundColor Yellow
git push origin main
Write-Host "Push successful!" -ForegroundColor Green
} else {
Write-Host "No changes detected, skipping commit." -ForegroundColor Gray
}
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Script execution completed" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
} catch {
Write-Host "Error: $_" -ForegroundColor Red
Write-Host "Stack trace: $($_.ScriptStackTrace)" -ForegroundColor Red
exit 1
}
+2
View File
@@ -66,3 +66,5 @@ else:
print("\n[SUCCESS] All required dependencies are installed!") print("\n[SUCCESS] All required dependencies are installed!")
sys.exit(0) sys.exit(0)
+3 -2
View File
@@ -78,12 +78,13 @@ if "stuck_guard_tick" not in globals():
# 清理局部变量,避免泄漏实现细节 # 清理局部变量,避免泄漏实现细节
# 注意:_name 和 _value 在 for 循环中定义,循环结束后会自动清理 # 注意:_name 和 _value 在 for 循环中定义,循环结束后会自动清理
# 但为了明确清理,我们显式删除 # 但为了明确清理,我们显式删除
# 使用 exec 来避免 pyright 的未绑定变量检查
try: try:
del _name exec("del _name")
except NameError: except NameError:
pass pass
try: try:
del _value exec("del _value")
except NameError: except NameError:
pass pass
try: try:
+28 -11
View File
@@ -138,7 +138,9 @@ def cleanup_old_logs(logs_dir: str, base_name: str, keep_days: int = 30) -> None
if deleted_count > 0: if deleted_count > 0:
try: try:
print(f"[日志清理] 已删除 {deleted_count} 个超过 {keep_days} 天的旧日志文件") print(
f"[日志清理] 已删除 {deleted_count} 个超过 {keep_days} 天的旧日志文件"
)
except Exception: except Exception:
pass pass
except Exception as e: except Exception as e:
@@ -207,7 +209,12 @@ def configure_logging(
global _logging_configured global _logging_configured
# 从 config.json 读取配置 # 从 config.json 读取配置
if log_level is None or log_file is None or keep_days is None or use_dated_logs is None: if (
log_level is None
or log_file is None
or keep_days is None
or use_dated_logs is None
):
try: try:
import json import json
@@ -295,9 +302,11 @@ def configure_logging(
# 启动时清理旧日志 # 启动时清理旧日志
if keep_days is not None: if keep_days is not None:
cleanup_old_logs(log_dir or path_config.get_logs_dir(), cleanup_old_logs(
os.path.basename(base_filename), log_dir or path_config.get_logs_dir(),
keep_days) os.path.basename(base_filename),
keep_days,
)
else: else:
# 使用传统的RotatingFileHandler # 使用传统的RotatingFileHandler
if log_file is None: if log_file is None:
@@ -510,15 +519,23 @@ def format_exception_info(exc_info=None) -> str:
return "".join(traceback.format_exception(exc_type, exc_value, exc_tb)) return "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
else: else:
# 如果不是异常实例,创建一个包装 # 如果不是异常实例,创建一个包装
return "".join(traceback.format_exception( return "".join(
exc_type, traceback.format_exception(
BaseException(str(exc_value)) if exc_value else BaseException("Unknown error"), exc_type,
exc_tb (
)) BaseException(str(exc_value))
if exc_value
else BaseException("Unknown error")
),
exc_tb,
)
)
else: else:
return "".join(traceback.format_exception(*exc_info)) return "".join(traceback.format_exception(*exc_info))
except Exception: except Exception:
return f"异常: {exc_info[1] if len(exc_info) > 1 and exc_info[1] else 'Unknown'}" return (
f"异常: {exc_info[1] if len(exc_info) > 1 and exc_info[1] else 'Unknown'}"
)
# 自动配置日志(在模块导入时) # 自动配置日志(在模块导入时)
+41 -12
View File
@@ -79,7 +79,9 @@ def detect_redpacket_popup_background(pic_rgb: Image.Image) -> bool:
return False return False
def detect_lucky_draw_result_popup(pic_rgb: Image.Image, red_ratio_threshold: float = 0.8) -> bool: def detect_lucky_draw_result_popup(
pic_rgb: Image.Image, red_ratio_threshold: float = 0.8
) -> bool:
"""检测抽奖结果弹窗:检测指定区域的红色占比("我知道了"按钮区域)。 """检测抽奖结果弹窗:检测指定区域的红色占比("我知道了"按钮区域)。
使用基准 1080x2400 坐标的检测区域: 使用基准 1080x2400 坐标的检测区域:
@@ -110,8 +112,11 @@ def detect_lucky_draw_result_popup(pic_rgb: Image.Image, red_ratio_threshold: fl
# 双截图记录:保存实时操作截图(像素检测区域) # 双截图记录:保存实时操作截图(像素检测区域)
try: try:
import douyin_screenshot_manager import douyin_screenshot_manager
detect_roi = pic_rgb.crop((x1, y1, x2, y2)) detect_roi = pic_rgb.crop((x1, y1, x2, y2))
douyin_screenshot_manager.save_latest_attempt(detect_roi, operation_type="pixel_detect") douyin_screenshot_manager.save_latest_attempt(
detect_roi, operation_type="pixel_detect"
)
except Exception: except Exception:
pass pass
@@ -142,8 +147,11 @@ def detect_lucky_draw_result_popup(pic_rgb: Image.Image, red_ratio_threshold: fl
if result: if result:
try: try:
import douyin_screenshot_manager import douyin_screenshot_manager
detect_roi = pic_rgb.crop((x1, y1, x2, y2)) detect_roi = pic_rgb.crop((x1, y1, x2, y2))
douyin_screenshot_manager.save_last_success(detect_roi, operation_type="pixel_detect") douyin_screenshot_manager.save_last_success(
detect_roi, operation_type="pixel_detect"
)
except Exception: except Exception:
pass pass
@@ -197,7 +205,9 @@ def detect_attend_button_red_area(pic_rgb: Image.Image) -> bool:
continue continue
# 如果红色像素占比足够高(至少25%),认为有大片红色背景 # 如果红色像素占比足够高(至少25%),认为有大片红色背景
total_samples = len(list(range(y1, y2, step_y))) * len(list(range(x1, x2, step_x))) total_samples = len(list(range(y1, y2, step_y))) * len(
list(range(x1, x2, step_x))
)
if total_samples == 0: if total_samples == 0:
return False return False
@@ -251,7 +261,9 @@ def detect_fansclub_join_red_area(pic_rgb: Image.Image) -> bool:
continue continue
# 如果红色像素占比足够高(至少25%),认为有大片红色背景 # 如果红色像素占比足够高(至少25%),认为有大片红色背景
total_samples = len(list(range(y1, y2, step_y))) * len(list(range(x1, x2, step_x))) total_samples = len(list(range(y1, y2, step_y))) * len(
list(range(x1, x2, step_x))
)
if total_samples == 0: if total_samples == 0:
return False return False
@@ -310,7 +322,13 @@ def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]:
total_samples += 1 total_samples += 1
# 检测白色/浅色(x图标):RGB值都较高且接近 # 检测白色/浅色(x图标):RGB值都较高且接近
if r > 200 and g > 200 and b > 200 and abs(r - g) < 30 and abs(g - b) < 30: if (
r > 200
and g > 200
and b > 200
and abs(r - g) < 30
and abs(g - b) < 30
):
white_count += 1 white_count += 1
# 检测粉色/红色(xin图标):R值高,G和B相对较低 # 检测粉色/红色(xin图标):R值高,G和B相对较低
@@ -338,7 +356,12 @@ def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]:
return False, 0.0 return False, 0.0
def detect_fudai_detail_page(pic_rgb: Image.Image, resolution_ratio_x: int = 1080, resolution_ratio_y: int = 2400, y_pianyi: int = 0) -> bool: def detect_fudai_detail_page(
pic_rgb: Image.Image,
resolution_ratio_x: int = 1080,
resolution_ratio_y: int = 2400,
y_pianyi: int = 0,
) -> bool:
"""检测是否处于福袋详情页。 """检测是否处于福袋详情页。
优先使用模板匹配检测标题区域(如“超级福袋”), 优先使用模板匹配检测标题区域(如“超级福袋”),
@@ -389,7 +412,11 @@ def detect_fudai_detail_page(pic_rgb: Image.Image, resolution_ratio_x: int = 108
template_path = os.path.join(base_dir, "assets", "xiangqing.png") template_path = os.path.join(base_dir, "assets", "xiangqing.png")
if os.path.exists(template_path): if os.path.exists(template_path):
template = cv2.imread(template_path, cv2.IMREAD_COLOR) template = cv2.imread(template_path, cv2.IMREAD_COLOR)
if template is not None and roi.shape[0] >= template.shape[0] and roi.shape[1] >= template.shape[1]: if (
template is not None
and roi.shape[0] >= template.shape[0]
and roi.shape[1] >= template.shape[1]
):
res = cv2.matchTemplate(roi, template, cv2.TM_CCOEFF_NORMED) res = cv2.matchTemplate(roi, template, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
# 固定阈值 0.7,后续如需可抽到配置 # 固定阈值 0.7,后续如需可抽到配置
@@ -463,10 +490,14 @@ def read_pixel_stage_state_from_screenshot(
detection_tasks = { detection_tasks = {
"has_coupon_bg": detect_coupon_popup_background, "has_coupon_bg": detect_coupon_popup_background,
"has_redpacket_bg": detect_redpacket_popup_background, "has_redpacket_bg": detect_redpacket_popup_background,
"has_lucky_draw_result": lambda pic: detect_lucky_draw_result_popup(pic, lucky_draw_red_ratio_threshold), "has_lucky_draw_result": lambda pic: detect_lucky_draw_result_popup(
pic, lucky_draw_red_ratio_threshold
),
"has_attend_button_red": detect_attend_button_red_area, "has_attend_button_red": detect_attend_button_red_area,
"has_fansclub_join_red": detect_fansclub_join_red_area, "has_fansclub_join_red": detect_fansclub_join_red_area,
"has_fudai_detail": lambda pic: detect_fudai_detail_page(pic, resolution_ratio_x, resolution_ratio_y, y_pianyi), "has_fudai_detail": lambda pic: detect_fudai_detail_page(
pic, resolution_ratio_x, resolution_ratio_y, y_pianyi
),
} }
# 使用线程池并行执行检测 # 使用线程池并行执行检测
@@ -488,5 +519,3 @@ def read_pixel_stage_state_from_screenshot(
state[key] = False state[key] = False
return state return state
+2
View File
@@ -65,3 +65,5 @@ def main():
if __name__ == "__main__": if __name__ == "__main__":
sys.exit(main()) sys.exit(main())
+1
View File
@@ -2,6 +2,7 @@
路径配置模块:统一管理所有文件路径,便于整理文件夹结构而不影响代码 路径配置模块:统一管理所有文件路径,便于整理文件夹结构而不影响代码
""" """
import os import os
from typing import Optional
# 项目根目录(所有路径的基准) # 项目根目录(所有路径的基准)
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
+2
View File
@@ -23,3 +23,5 @@ paddlepaddle>=2.5.0,<3.0.0
# 如果不安装ttkbootstrap,程序会自动使用原生tkinter # 如果不安装ttkbootstrap,程序会自动使用原生tkinter
# ttkbootstrap>=1.10.0 # ttkbootstrap>=1.10.0
+2
View File
@@ -39,3 +39,5 @@ ttkbootstrap>=1.10.0
# 2. 如果网络连接有问题,可以使用国内镜像源: # 2. 如果网络连接有问题,可以使用国内镜像源:
# pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple # pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
+5 -2
View File
@@ -8,6 +8,7 @@ import threading
import time import time
from http import HTTPStatus from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Optional
from urllib.parse import parse_qs, urlparse from urllib.parse import parse_qs, urlparse
BASE_DIR = os.path.dirname(__file__) BASE_DIR = os.path.dirname(__file__)
@@ -163,7 +164,7 @@ class ProcRunner:
def _inc(self, key: str, n: int = 1) -> None: def _inc(self, key: str, n: int = 1) -> None:
self._counters[key] = int(self._counters.get(key, 0)) + int(n) self._counters[key] = int(self._counters.get(key, 0)) + int(n)
def _record_event(self, typ: str, meta: dict | None = None) -> None: def _record_event(self, typ: str, meta: Optional[dict] = None) -> None:
ev = { ev = {
"ts": time.time(), "ts": time.time(),
"type": str(typ), "type": str(typ),
@@ -1320,7 +1321,9 @@ class Handler(BaseHTTPRequestHandler):
self.send_error(HTTPStatus.NOT_FOUND) self.send_error(HTTPStatus.NOT_FOUND)
def log_message(self, fmt, *args): def log_message(self, format, *args): # type: ignore[override]
# 覆盖基类方法以抑制日志输出
# 参数名从 fmt 改为 format 以匹配基类签名
return return
+108
View File
@@ -0,0 +1,108 @@
# Git自动提交和推送 - 设置说明
本说明将帮助您设置Windows任务计划程序,使Git每小时自动保存、提交并推送代码到GitHub。
## 方法一:使用Windows任务计划程序(推荐)
### 步骤1:打开任务计划程序
1. 按 `Win + R` 键,输入 `taskschd.msc`,然后按回车
2. 或者:开始菜单 → 搜索"任务计划程序" → 打开
### 步骤2:创建基本任务
1. 在右侧操作栏中,点击"创建基本任务"
2. 任务名称:`Git自动提交推送`
3. 描述:`每小时自动保存修改、提交并推送到GitHub`
4. 点击"下一步"
### 步骤3:设置触发器
1. 选择"每天"
2. 点击"下一步"
3. 开始时间:选择当前时间或任意时间
4. 重复任务间隔:选择"1小时"
5. 持续时间:选择"无限期"或设置结束日期
6. 点击"下一步"
### 步骤4:设置操作
1. 选择"启动程序"
2. 点击"下一步"
3. 程序或脚本:输入 `powershell.exe`
4. 添加参数:输入 `-ExecutionPolicy Bypass -File "C:\Users\12742\Desktop\douyin_guaji-main\auto_commit_push.ps1"`
5. 起始于:输入 `C:\Users\12742\Desktop\douyin_guaji-main`
6. 点击"下一步"
### 步骤5:完成设置
1. 勾选"当单击完成时,打开此任务属性的对话框"
2. 点击"完成"
### 步骤6:高级设置(重要)
在任务属性对话框中:
1. 切换到"常规"选项卡
- 勾选"不管用户是否登录都要运行"
- 勾选"使用最高权限运行"
- 配置:选择您的Windows版本(Windows 10/11)
2. 切换到"条件"选项卡
- 取消勾选"只有在计算机使用交流电源时才启动此任务"(如果使用笔记本)
3. 切换到"设置"选项卡
- 如果任务失败,立即启动任务:选择"是"
- 如果请求的任务正在运行:选择"并行运行新实例"或"停止现有实例"
4. 点击"确定"保存
### 步骤7:测试任务
1. 在任务计划程序中找到刚创建的任务
2. 右键点击 → 选择"运行"
3. 检查是否成功执行
## 方法二:使用PowerShell命令快速设置
您也可以使用以下PowerShell命令(以管理员身份运行)快速创建任务:
```powershell
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-ExecutionPolicy Bypass -File `"C:\Users\12742\Desktop\douyin_guaji-main\auto_commit_push.ps1`"" -WorkingDirectory "C:\Users\12742\Desktop\douyin_guaji-main"
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Hours 1) -RepetitionDuration (New-TimeSpan -Days 365)
$principal = New-ScheduledTaskPrincipal -UserId "$env:USERNAME" -RunLevel Highest
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable
Register-ScheduledTask -TaskName "Git自动提交推送" -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Description "每小时自动保存修改、提交并推送到GitHub"
```
## 注意事项
1. **Git凭据**:首次推送可能需要输入GitHub用户名和密码(或访问令牌)
- 建议使用Personal Access Token (PAT) 而不是密码
- 可以在GitHub设置中生成:Settings → Developer settings → Personal access tokens
2. **网络连接**:确保计算机连接到互联网,否则推送会失败
3. **Git配置**:确保已配置Git用户信息:
```bash
git config --global user.name "您的用户名"
git config --global user.email "您的邮箱"
```
4. **查看日志**:任务计划程序会记录每次执行的日志,可以在任务属性中查看历史记录
5. **手动测试**:您可以双击 `auto_commit_push.bat` 文件来手动测试脚本是否正常工作
## 停止自动提交
如果需要停止自动提交:
1. 打开任务计划程序
2. 找到"Git自动提交推送"任务
3. 右键点击 → 选择"禁用"或"删除"
## 修改提交频率
如果需要修改提交频率(例如每30分钟或每2小时):
1. 打开任务计划程序
2. 找到"Git自动提交推送"任务
3. 右键点击 → 选择"属性"
4. 切换到"触发器"选项卡
5. 编辑触发器,修改重复间隔
6. 保存更改